【问题标题】:How to make all images fit in same size div如何使所有图像适合相同大小的div
【发布时间】:2018-06-13 09:39:16
【问题描述】:

我希望它们都适合带边框的框,但我不希望它们看起来被拉伸。我该怎么做?

我尝试给它们一个固定的高度、div 内的宽度等,但它们看起来总是不太正确

<CategoryContainer>
    <CategoryLink to={`${category.name.toLowerCase()}`}>
        <CategoryImage>
            <Image image={category.products[0].image} />
        </CategoryImage>
        <CategoryName>
            {`${category.name}`}
        </CategoryName>
    </CategoryLink>
</CategoryContainer>

我的样式组件是:

export const Container = styled.div`
  display: flex;
  width: 1000px;
`;

export const CategoryContainer = styled.div`
  height: 300px;
  width: 33%;
  margin-right: 10px;
  position: relative;
  border: 1px solid black;
`;

export const CategoryLink = styled(Link)`
  text-decoration: none;
  color: black;
  z-index: 5;
  position: absolute;
`;

export const CategoryImage = styled.div`
`

export const CategoryName = styled.div`

`

【问题讨论】:

  • 请包含呈现的 HTML 和 CSS ...
  • max-height: 100%; max-width: 100%; 应该可以在大多数浏览器中使用,我记得这可能会导致某个地方的兼容性问题(我认为是 safari),但这是几年前的事情,现在可能已经解决了。不过,您不需要设置明确的高度或宽度,因为这会导致它倾斜。只有两个 max 属性,没有别的。
  • @jmcgriz max-width: 100%; max-height: 100%; width: auto; 我相信就足够了。
  • @DeepakKamat 但是我应该将这些应用到上面的哪个组件?
  • 图像,img 标记在您放置它们的容器内。

标签: javascript html css styled-components


【解决方案1】:

如果将图像设置为背景是一个选项: https://css-tricks.com/almanac/properties/b/background-size/

如果不是,请使用对象拟合:https://css-tricks.com/almanac/properties/o/object-fit/

【讨论】:

    【解决方案2】:

    一个相当简单的想法是保持宽度相对于高度。通常,大多数响应式图像的高度通过设置 height: autowidth: 100% 由其宽度控制,我们可以反转这一点,因为在您的情况下高度是可变的。

    .the-images {
      /* This is where magic happens */
      max-width: 100%;
      height: 100%;
      width: auto;
    
      display: block;
      margin: 0 auto;
    }
    

    如果盒子的宽度是流动的,或者为了保持纵横比,你可以这样做

    .the-images {
    
      /* This is where magic happens */
      max-width: 100%;
      max-height: 100%;
      width: auto;
    
      display: block;
      margin: 0 auto;
    }
    

    一个活生生的例子:

    http://jsbin.com/vuduvev/edit?css,output

    【讨论】:

      猜你喜欢
      • 2017-01-08
      • 2013-08-09
      • 1970-01-01
      • 1970-01-01
      • 2015-07-30
      • 1970-01-01
      • 2015-11-13
      • 2012-10-13
      • 1970-01-01
      相关资源
      最近更新 更多