Memor.の 2009-09-29 23:11 采纳率: 100%
浏览 465
已采纳

用 CSS 维护 div 的宽高比

I want to create a div that can change its width/height as the window's width changes.

Are there any CSS3 rules that would allow the height to change according to the width, while maintaining its aspect ratio?

I know I can do this via JavaScript, but I would prefer using only CSS.

div keeping aspect ratio according to width of window

转载于:https://stackoverflow.com/questions/1495407/maintain-the-aspect-ratio-of-a-div-with-css

  • 写回答

19条回答 默认 最新

  • 叼花硬汉 2012-05-04 01:19
    关注

    Just create a wrapper <div> with a percentage value for padding-bottom, like this:

    div {
      width: 100%;
      padding-bottom: 75%;
      background: gold; /** <-- For the demo **/
    }
    <div></div>

    It will result in a <div> with height equal to 75% of the width of its container (a 4:3 aspect ratio).

    This relies on the fact that for padding :

    The percentage is calculated with respect to the width of the generated box's containing block [...] (source: w3.org, emphasis mine)

    Padding-bottom values for other aspect ratios and 100% width :

    aspect ratio  | padding-bottom value
    --------------|----------------------
        16:9      |       56.25%
        4:3       |       75%
        3:2       |       66.66%
        8:5       |       62.5%
    

    Placing content in the div :

    In order to keep the aspect ratio of the div and prevent its content from stretching it, you need to add an absolutely positioned child and stretch it to the edges of the wrapper with:

    div.stretchy-wrapper {
      position: relative;
    }
    
    div.stretchy-wrapper > div {
      position: absolute;
      top: 0; bottom: 0; left: 0; right: 0;
    }
    

    Here's a demo and another more in depth demo

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(18条)

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧