0

As the following snippet shows, I am trying to define the dimensions of an element based on the width of their container, like defining an element's height in terms of the viewport width (e.g. width:100vw; height:56.25vw) but using the container's width rather than the viewport:

body {
  margin: 0;
}
div.fullwidth {
  background-color: #08B9E4;
  color: #fff;
  width: 100vw;
  height: 56.25vw;
  padding: 20px;
  box-sizing: border-box;
}
div.halfwidth {
  background-color: #08B9E4;
  color: #fff;
  width: 50vw;
  height: 28.125vw;
  padding: 20px;
  box-sizing: border-box;
}
div.fullwidth-container {
  width: 90vw;
  max-width: 600px;
  margin: 0 auto;
}
div.fullwidth-content1 {
  background-color: #08B9E4;
  color: #fff;
  width: 100vw;
  height: 56.25vw;
  padding: 20px;
  box-sizing: border-box;
}
div.fullwidth-content2 {
  background-color: #08B9E4;
  color: #fff;
  width: 100%;
  height: 56.25%;
  padding: 20px;
  box-sizing: border-box;
}
<p>By expressing the element's dimensions in viewport percentage units, I can define scalable elements with a fixed aspect ratio:</p>
<div class="fullwidth">
  This should fill the whole available width and its aspect ratio should be 16:9
</div>
<p>If I divide both width and height by the same scaling factor, I can get elements covering a partial width while maintaining their desired aspect ratio:</p>
<div class="halfwidth">
  This should fill half the available width and its aspect ratio should still be 16:9
</div>
<p>However, I would like the box to fill the whole width of its container, whatever that may be and possibly expressed in pixels rather than viewport percentage units, while remaining able to express the height as a percentage of the resulting width. But
  instead, it overflows its container because the units are expressed as a percentage of the viewport size, not the element's container:</p>

<div class="fullwidth-container">
  <div class="fullwidth-content1">
    This should fill the whole available width of the container
    <br/>and its aspect ratio should still be 16:9.
    <br/>Instead, it overflows its container.
    <br/>
  </div>
</div>
<p>If I express the width as a percentage (%) rather than a viewport percentage (vw), the element's width fits in nicely inside its container, but then I lose the aspect ratio because the height is now 56.25% of the container's height, which isn't even defined:</p>

<div class="fullwidth-container">
  <div class="fullwidth-content2">
    This should fill the whole available width of the container
    <br/>and its aspect ratio should still be 16:9.
    <br/>But it is not.
    <br/>
  </div>
</div>
<p>Is there a way to set a child element's height in relation to its width, and that in turn in relation to the size of its container, using only CSS?</p>

Is that possible using only CSS? Thanks!

Carvo Loco
  • 2,068
  • 13
  • 21

0 Answers0