更改浮动元素的顺序

时间:2018-06-06 14:37:39

标签: html css

我有以下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

4 个答案:

答案 0 :(得分:3)

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

&#13;
&#13;
.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;
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

仅浮动图像并保留另一个float:none

移除浮动

时请注意whitespace between inline-block

&#13;
&#13;
div {
  width: 33.33%;
  height: 50px;
}

#container {
  width: 100%;
}

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

#image {
  float: left;
}

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

答案 2 :(得分:0)

使用flexbox更改元素的顺序。也不需要漂浮。

.container {
  display: flex;
  justify-content: space-between;
}

#title {
  order: 2;
}

#image {
  order: 1;
}

#descr {
  order: 3;
}

@media only screen and (max-width: 480px) {
  div {
    width: 100%;
  }
}
<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>

答案 3 :(得分:0)

您必须相应地更改HTML代码中的顺序。如果你float: right两个元素,第一个元素将是最右边的,下一个元素就是它(如果有足够的空间)

&#13;
&#13;
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%;
  }
}
&#13;
<div id="image">This is an image</div>
<div id="descr">This is a description</div>
<div id="title">This is a title</div>
&#13;
&#13;
&#13;