首页 > 解决方案 > 超过移动设备上允许的最大宽度的网格容器

问题描述

由于某种原因,我的容器布局出现问题,它通过了容器的最大宽度 80rem 我无法想象如何解决这个问题,在我的其他网格布局中我没有这个问题最后我的问题是在移动设备上

示例:https ://codesandbox.io/s/twilight-mountain-t1c1m

代码:

<Container>
      <NewsWrapper>
        <CardTop>
          <div className="Bg" />
          <div className="headerH3">
            <h3>
              <a href="xd4">asdddddddddddddddddddddddddddddddddddd</a>
            </h3>
          </div>
        </CardTop>
        <CardTop>
          <div className="Bg" />
          <div className="headerH3">
            <h3>
              <a href="xd3">adssssssssssssssssssssssssssssssssssssss</a>
            </h3>
          </div>
        </CardTop>
        <CardTop>
          <div className="Bg" />
          <div className="headerH3">
            <h3>
              <a href="xd2">adsssssssssssssssssssssssssssssssssssssssss.</a>
            </h3>
          </div>
        </CardTop>
        <CardTop>
          <div className="Bg" />
          <div className="headerH3">
            <h3>
              <a href="xd">adssssssssssssssssssssssssssssssssss</a>
            </h3>
          </div>
        </CardTop>
      </NewsWrapper>
    </Container>

CSS:

export const Container = styled.div`
  background: none;
  height: 100%;
  margin: 0 auto;
  max-width: 80rem !important;
  padding-right: 15px;
  padding-left: 15px;
`;

export const NewsWrapper = styled.div`
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr;
  grid-column-gap: 10px;
  grid-row-gap: 15px;
  margin-top: 100px;
`;

export const CardTop = styled.div`
  position: relative;
  height: 300px;
  width: 100%;
  margin-bottom: 40px;
  & .Bg {
    display: flex;
    align-items: center;
    position: relative;
    background: red;
    background-size: cover;
    background-repeat: no-repeat;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    height: 200px;
    -o-background-size: cover;
    background-size: cover;
    background-position: center;
    cursor: pointer;
    :hover {
      box-shadow: inset 0 0 100px 100px rgba(0, 0, 0, 0.1);
    }
  }
  & .headerH3 {
    padding: 0 10px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  & > div > h3 {
    text-align: left;
    font-size: 1rem !important;
    font-family: Roboto Slab, serif;
    font-weight: 700;
    margin: 10px 0px 10px 0 !important;
  }
  & > div > h3 > a {
    text-decoration: none;
    color: #1976d5;
    display: block;
    clear: both;
    :hover,
    :active {
      filter: brightness(115%);
    }
  }
`;

编辑打印问题:

在此处输入图像描述

标签: css

解决方案


这样做的原因是grid-template-columns您的样式中定义的不允许换行。将其设置为grid-template-columns: 1fr 1fr 1fr 1fr将迫使浏览器尝试平均划分空间,使每个元素占总空间的四分之一。

您可以改为使用类似于 的东西grid-template-columns: repeat(auto-fit, minmax(250px,1fr));,它会尝试动态地适应列(如果屏幕尺寸不允许更大的尺寸,则将它们的尺寸限制为至少 250 像素)。您将需要自己处理容器内的溢出,但它至少会强制它换行。


推荐阅读