首页 > 解决方案 > 更改浮动元素的顺序

问题描述

我有以下 div 代码

div {
  float: left;
  width: 33.33%;
  height: 50px;
}

#container {
  width: 100%;
}

#title,
#image,
#descr {
  display: inline-block;
}

#title,
#descr {
  float: right;
}

@media only screen and (max-width: 480px) {
  div {
    width: 100%;
  }
}
<div id="title">This is a title</div>
<div id="image">This is an image</div>
<div id="descr">This is a description</div>

我想要做的是,排列 div,以便在桌面上首先显示图像,然后是标题和描述。像这样:

[This is an image] [This is a title] [This is a description]

但是,当我将标题和描述浮动到右侧时,我得到的结果是:

[This is an image] [This is a description] [This is a title]

另外,请不要说,虽然我可以更改 HTML 中 div 的顺序以获得我想要的顺序,但我希望标题在移动设备上排在第一位,然后是图像和描述,因此是顺序。

编辑:请注意,布局是通过浮动 div 来响应的。我正在寻找一种不完全移除浮动的解决方法。

jsfiddle

标签: htmlcss

解决方案


我会使用 flex 来做到这一点,因为它会更容易:

.container {
  display: flex;
  /* make things line up in a column */
  flex-direction: column;
}

.container>div {
  width: 100%;
  height: 50px;
}


/* do mobile first and media query for larger */

@media only screen and (min-width: 481px) {
  .container {
    /* make things line up in a row */
    flex-direction: row;
  }
  .container>div {
    width: 33.33%;
  }
  
  #title {
    order: 2;
  }
  #image {
    order: 1;
  }
  #descr {
    order: 3;
  }
}
<div class="container">
  <div id="title">This is a title</div>
  <div id="image">This is an image</div>
  <div id="descr">This is a description</div>
</div>


推荐阅读