【问题标题】:How do I make 2 or more horizontal divs stack into a vertical div when the user shrinks the browser window?当用户缩小浏览器窗口时,如何将 2 个或多个水平 div 堆叠成一个垂直 div?
【发布时间】:2013-03-07 07:34:31
【问题描述】:

我在同一行有 2 个 div,每个 div 的宽度为 50% 和一个浮点数:左。如果用户正在从智能手机查看页面,我希望他们将一个堆叠在另一个之上。现在,即使浏览器窗口缩小到 300 像素或从智能手机查看,这些 div 仍保留在同一行。

【问题讨论】:

  • 给 div 一个最小宽度,例如150像素

标签: css html layout liquid


【解决方案1】:

媒体查询是要走的路。我会采用移动优先的方法,并添加媒体查询以扩大设计。即,从 not 浮动的 div 开始,当屏幕空间达到一定大小时添加浮动和宽度:

<!-- HTML -->
<div class="wrapper">
    <div class="column">
        <p>This is column 1</p>
    </div>
    <div class="column">
        <p>This is column 2</p>
    </div>
</div>

/* CSS */
.wrapper {
    /* Ensure wrapper contains the columns, even when they are floated, by
       creating a new Block formatting context */
    overflow: hidden;
}

.column {
    /* Ensure we have some margins when the columns are collapsed, or 
       other content is displayed below. */
    margin-bottom: 2em;
}

/* Edit the min-width condition to match your desired breakpoint. */
@media screen and (min-width: 400px) {
    .wrapper .column {
        width: 50%;
        float: left;
    }
}

现场演示:http://jsfiddle.net/jPgWL/

【讨论】:

  • 帕特里克您好,非常感谢。此修复程序完美!我从来没有过多关注@media,因为我一直认为它对 css 最有用,因为它与打印网页有关。谢谢你:)
  • @AlexWilliams 不要忘记接受这个答案(点击支持按钮下方的绿色“眨眼”)。
  • 抱歉,我的声望必须至少达到 15 才能投票。现在我只有 11 岁 :(
【解决方案2】:

使用媒体查询:

@media screen and (min-width: 321px) {
  #wrapper {width: 100%;}
  .content {
    width: 50%;
    float: left;
  }
}
@media screen and (max-width: 320px) {
  #wrapper {width: 100%;}
  .content {
    width: 100%;
    float: none;
  }
}

【讨论】:

  • 这将是一个比仅仅添加 min-width 更清洁的解决方案,因为如果 div 被包装,它也会将宽度增加到 100%
猜你喜欢
  • 1970-01-01
  • 2016-08-20
  • 1970-01-01
  • 1970-01-01
  • 2012-03-22
  • 2015-12-01
  • 2017-12-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多