• 请不要在回答技术问题时复制粘贴 AI 生成的内容
kisshere
V2EX  ›  程序员

css 怎样让一张图片无论怎样缩放保持固定的长宽比?

  •  
  •   kisshere · May 28, 2019 · 5064 views
    This topic created in 2716 days ago, the information mentioned may be changed or developed.

    比如一张图片:800x800px, 怎样通过 css,让其长宽比始终保持 2:1,比如,设置该图片 width:100%,父 div 宽度 500px 的时候,该图片高度:250px ;父 div 宽度 300px 的时候,该图片高度:150px

    纯 css 不用 js 怎样实现?

    11 replies  •  2019-05-29 09:36:06 +08:00
    guojam
    guojam
    May 28, 2019
    1
    建议用 div+background,<img>标签不是很容易实现
    yimity
    yimity
    May 28, 2019
    2
    搜索一下图片百分比 img ratio,原理就是 padding-top 百分制的时候,参考计算使用的是 width,所以可以限制比例,然后 img absolute 就可以了。
    catteroLo
    catteroLo
    May 28, 2019
    3
    wednesdayco
    wednesdayco
    May 28, 2019
    4
    object-fit:contain;是不是你的需求- -
    KuroNekoFan
    KuroNekoFan
    May 28, 2019 via iPhone
    5
    object-fit 没错了
    IsaacYoung
    IsaacYoung
    May 28, 2019
    6
    padding-bottom: 50%;
    background: url(xxxx);
    molvqingtai
    molvqingtai
    May 28, 2019 via Android
    7
    利用父元素的 padding 撑出高度,img 绝对定位
    learnshare
    learnshare
    May 28, 2019❤️1
    9
    写一个 2:1 的容器,然后图片丢到容器里 100% * 100% 即可,方法楼上提到了多种

    实例 https://codepen.io/anon/pen/OYwOZd
    dr2009
    dr2009
    May 29, 2019
    10
    object-fit
    erda
    erda
    May 29, 2019
    11
    var + calc 也可以实现
    栗子: https://codepen.io/Erdayo/pen/YbOyOa
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5067 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 44ms · UTC 07:36 · PVG 15:36 · LAX 23:36 · JFK 02:36
    ♥ Do have faith in what you're doing.