img width relative to containing div

Unfortunately, CSS has no parent selector. While you can’t make an element relative to the parent directly with CSS, what you can do with pure CSS is set a variable that both elements make use of:

:root {
--width: 90vw; // Must be viewport-driven
}

Now you can use this variable as both the (fixed) width of the parent element, and the calculation-driven width of the child:

#under {
  width: var(--width);
}

#image1 {
  width: calc(var(--width) / 3); // The 3 can be replaced with any float
}

Note that the variable must either be a fixed unit, or be relative to the viewport. If it were percentage-based, both #under and #image1 would base their width off of their respective parents. In order to have this work responsively, it must be based off of the viewport.

:root {
--width: 90vw;
}

div {
  position: relative;
  display: block;
  width: 100%;
}

#image1 {
  position: absolute;
  left: 10%;
  top: 10%;
  width: calc(var(--width) / 3);
  height: auto;
}

#image2 {
  position: absolute;
  left: 25%;
  top: 10%;
  width: 10%;
  height: auto;
}

#under {
  width: var(--width);
}
<div>
  <img id="image1" src="http://placehold.it/206x115">
  <img id="under" src="http://placehold.it/700x300/ff00f0/ffffff">
</div>

I’ve also created a JSFiddle of this here, where you can see both elements scale when the viewport resizes.

Hope this helps! 🙂

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)