子高度作为CSS3中父宽度的函数

时间:2016-08-25 11:19:03

标签: css3 viewport-units

如下面的代码片段所示,我试图根据容器的宽度定义元素的尺寸,比如根据视口宽度定义元素的高度(例如width:100vw; height:56.25vw)但是使用容器的宽度而不是视口:

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>

这只能使用CSS吗?谢谢!

0 个答案:

没有答案