【问题标题】:Swap div position with media query用媒体查询交换 div 位置
【发布时间】:2016-05-15 00:42:22
【问题描述】:

当浏览器宽度低于 600 像素时,我想要这样的位置变化,这要归功于媒体查询:

看来这需要交换div的位置。这可以通过 CSS 实现吗?

* { padding: 0; margin: 0; }
#a { float: left; background-color: red; width: 150px; }
#b { background-color: blue; }
#c { float: right; width: 40%; background-color: yellow; }
@media (max-width: 600px) { 
        /* ... */
}
<div>
   <div id="a">a</div>
   <div id="c">c</div>
   <div id="b">b</div>
</div>

【问题讨论】:

    标签: html css css-float media-queries


    【解决方案1】:

    您只需要重置浮动或宽度属性。

    在处理浮动和非浮动元素时,请注意 BFC 块格式化上下文。

    http://www.sitepoint.com/understanding-block-formatting-contexts-in-css/

    * {
      padding: 0;
      margin: 0;
    }
    #a {
      float: left;
      background-color: red;
      width: 150px;
    }
    #b {
      background-color: blue;
    }
    #c {
      float: right;
      width: 40%;
      background-color: yellow;
    }
    @media (max-width: 600px) {
      #c {    
        width: 100%;
      }
    }
    <div>
      <div id="a">a float</div>
      <div id="c">c float or not</div>
      <div id="b">b</div>
    </div>

    【讨论】:

    【解决方案2】:

    是的,可以使用 CSS。事实上,使用 flexbox 很容易,它就是为这样的任务而设计的。

    * {
      padding: 0;
      margin: 0;
    }
    
    #container {
      display: flex;                    /* establish flex container */
    }
    
    #a {
      flex: 0 0 150px;                  /* don't grow, don't shrink, fixed at 150px width */
      background-color: red;
    }
    #b {
      flex: 1;                          /* consume all available free space in the row */
      background-color: aqua;
    }
    #c {
      flex: 0 0 40%;                    /* don't grow, don't shrink, fixed at 40% width */
      background-color: yellow;
    }
    @media (max-width: 600px) {
      #container { flex-wrap: wrap; }        /* allow flex items to wrap */
      #b { flex-basis: calc(100% - 150px); } /* take full width less width of #a */
      #c { flex-grow: 1; }                   /* consumer all available free space in the row */
    }
    <div id="container"><!-- children ordered chronologically; no need to reverse order -->
      <div id="a">a</div>
      <div id="b">b</div>
      <div id="c">c</div>
    </div>

    要了解有关 flexbox 的更多信息,请访问:


    flexbox 的好处:

    1. 最小代码;非常高效
    2. centering, both vertically and horizontally, is simple and easy
    3. equal height columns are simple and easy
    4. multiple options for aligning flex elements
    5. 反应灵敏
    6. 与浮动和表格不同,它们提供有限的布局容量,因为它们从未用于构建布局,flexbox 是一种现代 (CSS3) 技术,具有广泛的选项。

    浏览器支持:

    所有主流浏览器都支持 Flexbox,except IE 8 & 9。一些最新的浏览器版本,例如 Safari 8 和 IE10,需要vendor prefixes。要快速添加所需的所有前缀,请使用Autoprefixer。更多详情请见this answer

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 2014-03-18
      • 1970-01-01
      相关资源
      最近更新 更多