【问题标题】:CSS Maintain Aspect Ratio not workingCSS保持纵横比不起作用
【发布时间】:2018-09-28 19:40:59
【问题描述】:

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

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

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>

【问题讨论】:

  • 我已经和朋友们确认他们也看到了一个高长的矩形而不是一个正方形......这没有任何意义
  • 它以父代的百分比计算,一如既往。在您链接的答案中,元素的宽度为 100%,因此子元素的宽度与父元素的宽度相同
  • 天啊!金发碧眼的时刻..这里没什么可看的:D
  • @RickSibley 我只是将 .test div 放在 .parent 中,目的是为了证明它正在查看父级......我认为这是不正确的行为。我认为它是为了从 .test 中获取它的填充值,并且应该给我一个正方形。很抱歉造成混乱。这是代表我的脑放屁。
  • 好像你在要求这样的东西:jsfiddle.net/MpXYr/5128;但我可能只是误解了。

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


【解决方案1】:

这实际上是正确的行为。您的目的是让孩子 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/

【讨论】:

    【解决方案2】:

    CSS 对此有一个属性

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

    更新:
    还有另一种方法,如果您的支持绝对至关重要,并且您无法忍受 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*/
    &lt;div&gt;hello&lt;/div&gt;

    【讨论】:

    • aspect-ratio prop 并不是所有主流浏览器都支持它有什么意义?
    • 不aspect ratio 使代码更具可读性而不是hacks
    • 现在没有了。由于它的支持,仍然必须使用 hacks
    • 我认为 firefox 不支持纵横比,但我不在乎我的网站是否面向该市场。
    • 如果您的网站上有 1 个潜在用户,就会采用这种方法
    猜你喜欢
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 2019-08-03
    • 2018-04-02
    • 2018-03-11
    • 1970-01-01
    • 2019-05-12
    相关资源
    最近更新 更多