NewbieAeg
NewbieAeg

Reputation: 637

Setting image opacity with styled-components

I've been trying to set an opacity for my background image but the only thing opacity changes is basically everything beside the image. How do I change the attributes of my body using styled components?

import styled, { createGlobalStyle } from "styled-components";
import Clouds from "./Pics/Clouds.png";

const GlobalStyle = createGlobalStyle`
  body {
    background-image: url(${Clouds});
  }
`;

const StyledText = styled.div`
  text-align: justify;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
  font-size: 35px;
  font-family: "Comic Sans MS";
`;

const Weather = (props) => {
  return (
    <React.Fragment>
      {" "}
      <StyledText>
        Today : {props.main}
        <br />
        City : {props.city}
        <br />
        Celcius: {props.temp}
        <br />
      </StyledText>
      <GlobalStyle />
    </React.Fragment>
  );
};

export default Weather;

Thanks for any kind of help!

Upvotes: 1

Views: 5378

Answers (2)

PetarBoshkoski
PetarBoshkoski

Reputation: 21

I am not quite sure which element you want to set opacity on. But, fun thing is that you can pass props when rendering your styled component, and catch them in your styled component definition.

First you define your image component inside a div.

const StyledImage = styled.div`
    background-image: url("example.jpg")
    opacity: ${props => props.imgOpacity}
`;

When calling the s. component, you set your opacity:

<StyledImage imgOpacity={"0.5"} />

Using props is a cool way of reusing styles for your styled components and preventing styles from interfering with other elements.

Upvotes: 1

giovanni
giovanni

Reputation: 388

You can’t set opacity on a background property, You have two options here as far as I see Either you use an image already “opacizied” Or you use a different component/element as you background and add the opacity to the element itself like in the example below

import styled, { createGlobalStyle } from "styled-    components";
import Clouds from "./Pics/Clouds.png";

const YourBg = styled.div `
  background-image: url(${Clouds});
  opacity: 0.5;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
`;

const StyledText = styled.div`
  text-align: justify;
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -100px;
  font-size: 35px;
  font-family: "Comic Sans MS";
`;

const Weather = (props) => {
  return (
    <React.Fragment>
      {" "}
      <YourBg />
      <StyledText>
        Today : {props.main}
        <br />
        City : {props.city}
        <br />
        Celcius: {props.temp}
        <br />
      </StyledText>
    </React.Fragment>
  );
};

export default Weather;

Upvotes: 0

Related Questions