How do I get the current height and width of a background image

101 Views Asked by At

The problem that I'm facing is that the image height is not scaling with the width as I want it to. I have tried background-size: cover and background-size: contain as well as using object-fit. None of those options is giving me what I intend: having the height of the conteiner depend on the width of the container.

I figured that the height percentage of the current width should be height:calc(currentHeight/currentWidth*100). Now I thought of using useRef from react to get the current values everytime the window size changes with an onLoad fuction but I don't know how to target the svg that is being loaded in my CSS. All examples that I have encountered are using the img tag.

Background image CSS:

const Background = styled.section`
  border: solid 1px red;
  background: url(${Donationsvg}) no-repeat center;
  background-size: contain;
  width: 100%;
  height: 100%;
`;

Page content structure:

<Background>
        <Grid>
  
           <Card>
              <Button>
                <h4>title</h4>
              </Button>
              <p>Lorem ipsum dolor sit amet consectetur adipisic.</p>
            </Card>

            <Card>
              <Button>
                <h4>title</h4>
              </Button>
              <p>Lorem ipsum dolor sit amet consectetur adipisic.</p>
            </Card>

            <Card>
              <Button>
                <h4>title</h4>
              </Button>
              <p>Lorem ipsum dolor sit amet consectetur adipisic.</p>
            </Card>
          
<Background>

1

There are 1 best solutions below

0
Franco Hauva On

Found a solution using padding, since the percentage value for padding is based off the parent element's width. Instead of using height I used padding-block:10% and background-size:cover.

const Background = styled.section`
  border: solid 1px red;
  background: url(${Donationsvg}) no-repeat center;
  background-size: cover;
  width: 100%;
  padding-block: 10%;
`;