【问题标题】:Flex: Resize image to content in cross axisFlex:将图像大小调整为横轴上的内容
【发布时间】:2021-05-08 17:35:46
【问题描述】:

我有一个弹性容器,里面有两个弹性项目:一个 H1 和一个 IMG。

弯曲方向是行。

我希望横轴(垂直)中两个项目的大小由 H1 的高度决定。

当 H1 的高度大于图像的原始分辨率时,这可以正常工作,图像会缩放以匹配 H1 的高度。

*
{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body
{
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}
h1
{
  font-size: 250px;
}
<body>
    <h1>Hi</h1>
    <img src="https://revmd.com/wp-content/uploads/medical-coding-icon.jpg" alt="">
</body>

但是,当 H1 的高度小于图像的原始分辨率时,图像不会调整到 H1 的高度,而是由其默认分辨率决定。

我怎样才能达到想要的效果,最好保留图像的纵横比?

【问题讨论】:

    标签: css image flexbox


    【解决方案1】:

    设置图像的高度和宽度等于文本的数字字体大小。并拥有object-fit:contain 以保持图像的纵横比

    *
    {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    }
    body
    {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
    }
    h1
    {
      font-size: 20px;
    }
    img {
    width: 20px;
    height: 20px;
    object-fit:contain;
    }
    <body>
        <h1>Hi</h1>
        <img src="https://revmd.com/wp-content/uploads/medical-coding-icon.jpg" alt="">
    </body>

    【讨论】:

      猜你喜欢
      • 2018-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-23
      • 2015-12-21
      • 2017-05-28
      • 2014-06-03
      • 1970-01-01
      相关资源
      最近更新 更多