CSS保持纵横比不起作用

标签 css responsive-design responsive aspect-ratio browser-bugs

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

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

Maintain the aspect ratio of a div with CSS

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

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

.parent {
  width: 200px;
}

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

最佳答案

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>

关于CSS保持纵横比不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901814/

相关文章:

javascript - 动画没有按预期工作

css - 剪辑路径在 Firefox 和 IE 中不起作用

javascript - slideToggle() 导致第一个 li a 在点击时跳转

html - 在 html 和 css 中构建带有图片响应的 2 div

html - 图像缩小并显示在屏幕中间

html - 响应图像,固定比例。无法让代码工作

css - 带有 CSS 变量的文本阴影

javascript - 浏览器窗口响应内容

html - 如何在 Angular 组件styles.scss中使用媒体查询?

javascript - 垂直居中图像,基于容器高度