响应式页面:当处于单列模式时,使右侧栏始终保持在顶部

6
我有以下的HTML标记:
<div class="left">
this is left side. it should go to the bottom when in one column
</div>
<div class="right">
this is right side. it should go to the top when in one column
</div>

CSS:

.left {
    width: 70%;
    float: left;
    background-color: red;
}
.right {
    width: 30%;
    float: left;
    background-color: yellow;
}

 @media only screen and (max-width : 768px) {
   .left, .right {
        width: 100%;
     }
}

我希望在显示为单列时,右侧栏能保持在顶部。
这是 jsfiddle 的链接:https://jsfiddle.net/m7zpoc30/1/ 请问我需要做什么,包括对当前 CSS 的更改?

3
调换你的div顺序并将右边的div向右浮动。 - JonSG
3个回答

8

以下是一种使用 flex 的解决方案,可能会有所帮助。您可以将左右两个 div 包装在一个具有 display:flex 属性的容器中,然后在调整大小时使用 flex-direction。请参见下面的代码片段。(jsfiddle

.container {
  display: flex;
  
}

.left {
  width: 70%;
  background-color: red;
}

.right {
  width: 30%;
  background-color: yellow;
}

@media only screen and (max-width: 768px) {
  .container {
    flex-direction: column-reverse;
  }
  .left, .right {
    width: 100%;
  }
  
}
<div class="container">
  <div class="left">
    this is left side. it should go to the bottom when in one column
  </div>
  <div class="right">
    this is right side. it should go to the top when in one column
  </div>
</div>


感谢您提供的解决方案!我选择了另一个答案,因为对我的代码更改最小。我已经给您的答案点赞了。 - curious1

6

1

以下是使用order flex属性的替代解决方案。请参见下面的代码片段。

.container {
  display: flex;
  
}

.left {
  width: 70%;
  background-color: red;
  order: 1;
}

.right {
  width: 30%;
  background-color: yellow;
  order: 2;
}

@media only screen and (max-width: 768px) {
  .container {
    flex-direction: column;
  }
.left {
    order: 2;
  }
.right {
    order: 1;
  }
}
<div class="container">
  <div class="left">
    this is left side. it should go to the bottom when in one column
  </div>
  <div class="right">
    this is right side. it should go to the top when in one column
  </div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接