如何使所有图像适合相同大小的div

时间:2018-01-03 17:11:57

标签: javascript html css styled-components

enter image description here

我希望它们都适合带有边框的盒子,但我不希望它们显得拉伸。我怎么能这样做?

我试过给他们一个固定的高度,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`

`

2 个答案:

答案 0 :(得分:0)

如果将图像设置为背景,则可以选择: https://css-tricks.com/almanac/properties/b/background-size/

如果没有,请使用object-fit:https://css-tricks.com/almanac/properties/o/object-fit/

答案 1 :(得分:0)

一个相当简单的想法是保持宽度相对于高度。通常,通过设置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