【问题标题】:Why is row with column cards layout not working?为什么带有列卡布局的行不起作用?
【发布时间】:2021-10-12 02:39:18
【问题描述】:

我正在建立一个网站,我试图在其中创建一行 2 列卡片。当屏幕尺寸缩小时,我也希望它变成一张排卡。

相反,它停留在单行格式。

我已经附上了我正在尝试做的事情的图片(颜色无关紧要)

这是 HTML:

<div class="row">
    <div class="column">Box 1</div>
    <div class="column">Box 2</div>
</div>

这是 CSS:

.column {
    background-color: black ;
    float: left;
    width: 50%;
    padding: 50px;
    text-align: center;
    font-size: 25px;
    color: white;
}

【问题讨论】:

标签: html css web layout


【解决方案1】:

请注意,填充会影响宽度,因此 .column div 会扩展超过屏幕宽度的 50%。

除非您想学习,否则我建议您使用 CSS 框架,例如 Bootstrap。在管理布局时,它们让生活变得非常轻松。

【讨论】:

    【解决方案2】:

    您想要的可以通过媒体查询和 CSS 网格布局来实现:

    .column {
        background-color: black;
        padding: 50px;
        margin: 5px;
        text-align: center;
        font-size: 25px;
        color: white;
    }
    
    .row {
      display: grid;
      grid-template-columns: 1fr 1fr;
    }
    
    @media(max-width: 500px) {
      .row {
        grid-template-columns: 1fr;
      }
    }
    <div class="row">
        <div class="column">Box 1</div>
        <div class="column">Box 2</div>
    </div>

    【讨论】:

      【解决方案3】:

      .column {
          background-color: black ;
          width: calc(50% - 100px);
          padding: 50px;
          text-align: center;
          font-size: 25px;
          color: white;
          display: block;
      }
      
      @media (min-width: 102px) {
          .column {
              float: left;
          }
      }
      <div class="row">
          <div class="column">Box 1</div>
          <div class="column">Box 2</div>
      </div>

      您可以为此目的使用媒体查询,您需要找到限制,为了示例,我给出了 102px,但您需要找到最适合您的情况的像素限制,可能是同步的手机屏幕尺寸。

      它卡在一个下面的盒子的原因是你有一个 50px 的填充,所以整个宽度是 2 * (50% + 50px) = 100% + 100px,如果你添加任何正值到 100%,那么这两个项目将不适合单行。然后, float:left 仅在我们以内联方式显示它们时才需要。因此,float:left 仅在一种情况下需要,您需要进行计算以从 div 中提取 100px 像素。最后,我添加了 display: 块。编码愉快!

      【讨论】:

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