Html 使用padding-bottom-aspect-ratio hack强制图像保持::before的尺寸

Html 使用padding-bottom-aspect-ratio hack强制图像保持::before的尺寸,html,css,reactjs,styled-components,aspect-ratio,Html,Css,Reactjs,Styled Components,Aspect Ratio,我正在使用::before和内容:“”;填充底部:100%尝试在图像上强制执行1:1纵横比的技巧。我还添加了溢出:隐藏。但是,正如您从屏幕截图中看到的,图像溢出了我在::before中创建的正方形之外。我根本不希望图像拉伸,因此所有图像都应用了objectfit:contain 我遵循了一个关于纵横比的公式 我如何才能确保图像整齐地放在那个正方形中,而不会溢出 编辑: 代码如下: 项目1.tsx <StyledItemWrapper className={item.animation}

我正在使用
::before
内容:“”;填充底部:100%
尝试在图像上强制执行1:1纵横比的技巧。我还添加了
溢出:隐藏
。但是,正如您从屏幕截图中看到的,图像溢出了我在
::before
中创建的正方形之外。我根本不希望图像拉伸,因此所有图像都应用了
objectfit:contain

我遵循了一个关于纵横比的公式

我如何才能确保图像整齐地放在那个正方形中,而不会溢出

编辑:

代码如下:

项目1.tsx

<StyledItemWrapper
  className={item.animation}
  onClick={() => {
    clickItem(item);
  }}
>
  <picture>
    <img src={item.image} alt={item.title} />
  </picture>
  <StyledItemInfo>
    <p>{item.title}</p>
    <p>{item.description}</p>
    <p>${item.price.toFixed(2)}</p>
  </StyledItemInfo>
  <Button onClick={() => handleAddToCart(item)}>Add To Cart</Button>
</StyledItemWrapper>
const Item: React.FC<Props> = ({ item, handleAddToCart, clickItem }) => (
  <StyledItemWrapper
    className={item.animation}
    onClick={() => {
      clickItem(item);
    }}
  >
    <StyledVisualWrapper> // new styled component
      <picture>
        <img src={item.image} alt={item.title} />
      </picture>
    </StyledVisualWrapper>
    <StyledItemInfo>
      <p>{item.title}</p>
      <p>{item.description}</p>
      <p>${item.price.toFixed(2)}</p>
    </StyledItemInfo>
    <Button onClick={() => handleAddToCart(item)}>Add To Cart</Button>
  </StyledItemWrapper>
);

问题是,我将styled应用于
StyledItemRapper
,它包装了整个卡,而不仅仅是图像,因此任何填充等都会影响整个卡的布局

只有将纵横比填充和伪选择器应用于专用图像容器时,它才有效。所以,这就是我所做的:

项目1.tsx

<StyledItemWrapper
  className={item.animation}
  onClick={() => {
    clickItem(item);
  }}
>
  <picture>
    <img src={item.image} alt={item.title} />
  </picture>
  <StyledItemInfo>
    <p>{item.title}</p>
    <p>{item.description}</p>
    <p>${item.price.toFixed(2)}</p>
  </StyledItemInfo>
  <Button onClick={() => handleAddToCart(item)}>Add To Cart</Button>
</StyledItemWrapper>
const Item: React.FC<Props> = ({ item, handleAddToCart, clickItem }) => (
  <StyledItemWrapper
    className={item.animation}
    onClick={() => {
      clickItem(item);
    }}
  >
    <StyledVisualWrapper> // new styled component
      <picture>
        <img src={item.image} alt={item.title} />
      </picture>
    </StyledVisualWrapper>
    <StyledItemInfo>
      <p>{item.title}</p>
      <p>{item.description}</p>
      <p>${item.price.toFixed(2)}</p>
    </StyledItemInfo>
    <Button onClick={() => handleAddToCart(item)}>Add To Cart</Button>
  </StyledItemWrapper>
);