0

这是最奇怪的事情,我以前曾多次使用过这种方法,但现在它似乎对我来说很糟糕。

这是提供此方法作为答案的重复问题:

使用 CSS 保持 div 的纵横比

但是由于某种未知的原因,它在 Firefox 和 Chrome 中对我来说很糟糕。据我所知,它正在根据我将样式应用到的元素的父元素计算填充...

在这种情况下,它不查看,.test而是查看.parent计算填充:

.parent {
  width: 200px;
}

.test {
  width: 50px;
  background: red;
  padding-top: 100%;
}
<div class='parent'>
  <div class='test'></div>
</div>

4

2 回答 2

2

这实际上是正确的行为。您的目的是让孩子 100% 宽度并与父母一起控制尺寸。

例子:

.parent {
  width: 200px;
}

.child {
  width: 100%;
  background: red;
  padding-top: 100%;
}
<div class="parent">
  <div class="child"></div>
</div>

这是在 CSS-Tricks 上提出的一个很好的方法,可以帮助您获得所需比例所需的正确填充:

纵横比 - 2:1

.parent {
  width: 200px;
}

.child {
  width: 100%;
  background: red;
  padding-top: calc(1 / 2 * 100%); // will give you an aspect ratio of 2:1
}
<div class="parent">
  <div class="child"></div>
</div>

纵横比 - 3:1

.parent {
  width: 200px;
}

.child {
  width: 100%;
  background: red;
  padding-top: calc(1 / 3 * 100%); // will give you an aspect ratio of 3:1
}
<div class="parent">
  <div class="child"></div>
</div>

纵横比 - 16:9

.parent {
  width: 200px;
}

.child {
  width: 100%;
  background: red;
  padding-top: calc(9 / 16 * 100%); // will give you an aspect ratio of 16:9
}
<div class="parent">
  <div class="child"></div>
</div>

你可以在这里找到完整的文章: https ://css-tricks.com/aspect-ratio-boxes/

于 2018-04-18T15:00:15.677 回答
2

CSS对此有一个属性

.square {
  aspect-ratio: 1 / 1;
  width: 100px;
  background: grey;
  padding: 10px;
  color: white;
}
<div class="square">a sqaure</div>

更新:
如果您的支持绝对至关重要,并且您无法忍受 Firefox 不受支持,那么还有另一种方法。但它有点笨拙。

div {
width: 5em;
height: 5em;
font-size: 3vw; background: grey; padding: 0.5em;}

/*em is relative to font-size so you could use that and vw is veiwport width where 100 is all of the veiwport. the size of the shape is now 5 * 3vh*/
<div>hello</div>

于 2021-02-16T10:59:09.253 回答