CSS3宽度和容器的高度百分比

时间:2018-01-09 17:27:06

标签: css twitter-bootstrap css3

我需要做类似问题的事情

Maintain the aspect ratio of a div with CSS

我有两个单元格的引导网格,每个单元格在移动设备上每个

我想插入一个固定比例为4:3的盒子,我不能使用视口宽度和高度比例,因为内容已经在bootstrap单元格内

我想知道在CSS3中是否可以根据父宽度表示元素的宽度和高度



#box-01,
#box-02 {
  width: 20vw;
  height: 15vw;
  background: gold;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
  <div class="col-sm-6">
    <div id="box-01">4:3</div>
  </div>
  <div class="col-sm-6">
    <div id="box-02">4:3</div>
  </div>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

据我所知,你有一种可能性。

注意:认为这是一个可能不应该在生产代码中使用的黑客。

marginpadding属性的百分比值相对于包含块的 width 。这意味着margin-toppadding-top(沿Y轴运行)将响应对父项宽度的更改(沿X轴运行)。

在以下示例中,.child的宽度为50%,相对于父级的宽度。要让 height 响应父级的 width ,我们可以使用padding-top属性来模拟高度。现在.child的宽度和模拟高度都相对于.parent的宽度,从而保留了宽高比。

(尝试调整.parent的大小以了解.child如何在保持宽高比的同时做出响应。)

&#13;
&#13;
.parent {
  width: 200px;
  height: 150px;
  background: orange;
  overflow: scroll;
  resize: both;
  border: 1px solid #999;
}
.child {
  margin: auto;
  width: 50%;
  height: 0;
  padding-top: calc(50% * 0.75);
  background: yellow;
}
&#13;
<div class="parent">
    <div class="child"></div>
</div>
&#13;
&#13;
&#13;

现在,正如任何人都会很快发现的那样,这不允许.child内的任何内容。要解决此问题,您可以引入另一个名为<div>的嵌套.grand-child。使.child相对定位,.grand-child绝对定位在.child内。

&#13;
&#13;
.parent {
  width: 200px;
  height: 150px;
  background: orange;
  overflow: scroll;
  resize: both;
  border: 1px solid #999;
}
.child {
  position: relative;
  margin: auto;
  width: 50%;
  height: 0;
  padding-top: calc(50% * 0.75);
  background: yellow;
}
.grand-child {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background: red;
}
&#13;
<div class="parent">
    <div class="child">
        <div class="grand-child">
            Hello world
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

相关问题