【问题标题】:CSS responsive horizontal and vertical layoutCSS 响应式水平和垂直布局
【发布时间】:2017-03-02 04:03:08
【问题描述】:

我正在尝试构建响应式布局:

小视口(例如最大宽度 750 像素):

    +---------------+
    |      1        |
    +----+-----+----+
    |  2 |     |    |
    +----+  4  |  5 |
    |  3 |     |    |
    +----+-----+----+

大视口(最小宽度 751px):

    +---+---+---+---+
    | 1 |   |   |   |
    +---+ 3 | 4 | 5 |
    | 2 |   |   |   |
    +---+---+---+---+

我尝试过使用 flex、display: table 等。我找到的唯一解决方案是复制标记,但这并不理想。还有没有其他可能?

框具有可变长度的文本内容,因此很遗憾固定高度不是一个选项。

【问题讨论】:

  • flex 应该可以工作。具体检查order flex 属性。
  • ..也提供你试过的代码。
  • 使用bootstrap 网格结构。它将以多种方式帮助您进行响应式设计。这是link
  • @Mr_Green flex 的问题是我不能只使用一个 flex 容器来实现它。我需要两个单独的 flex 容器(一个用于垂直对齐的盒子,一个用于其他盒子),所以顺序不是一个选项。

标签: html css layout responsive-design responsive


【解决方案1】:

我是使用 flexboxposition: relative 完成的。

Working Fiddle

.parent {
  display: flex;
  flex-wrap: wrap;
  height: 400px;
}
.box {
  box-shadow: inset 0px 0px 0px 1px #ccc;
  flex: 1;
  height: calc(100% / 3);
  line-height: 150px;
  text-align: center;
  position: relative;
}
.one {
  flex: 1 0 100%;
}
.two,
.four,
.five,
.six {
  flex: 1 0 calc(100% / 3);
  /*   min-width: calc(100% / 4) */
}
.four,
.five,
.six {
  height: calc(200% / 3);
}
.three {
  order: 1;
  max-width: calc(100% / 3);
  top: calc(-100% + (200% / 3));
}
@media (max-width: 500px) {
  .one {} .one,
  .two,
  .three,
  .four,
  .five {
    flex: 1 0 calc(100% / 4);
    max-width: calc(100% / 4);
    top: 0px;
  }
  .one,
  .two {
    height: calc(100% / 2);
  }
  .three,
  .four,
  .five {
    height: 100%;
  }
  .two {
    order: 1;
    top: calc(-100% / 2);
  }
  .three {
    order: 0;
  }
}
<div class="parent">
  <div class="box one">1</div>
  <div class="box two">2</div>
  <div class="box three">3</div>
  <div class="box four">4</div>
  <div class="box five">5</div>
</div>

【讨论】:

  • 谢谢!这正是我想要的,但容器的高度取决于内容,所以我不能为容器和盒子设置 fixed height :/
  • @edo 我建议你在你的问题中解释同样的问题。
【解决方案2】:

.header{
  width:100%;
  height:100px;
  border:1px solid #ff9900;
}
.l1,.l2{
  width:33%;
  float:left;
  border:1px solid green;
  height:100px;
  margin-right:1px;
}
.l3{
  float:right;
  width:32%;
  height:100px;
  border:1px solid red;
}
.a1,.a2,.a3,.a4{
  width:24%;
  float:left;
  border:1px solid green;
  height:100px;
  margin-right:1px;
}
<div class="header">
<h1>header</h1>
</div>
<div class="body">
<div class="l1">
  <div style="width:100%; height:50%; background:#ff8800;">1</div>
  <div style="width:100%; height:50%; background:#ffff00;">2</div>
  </div>
  <div class="l2">3</div>
  <div class="l3">4</div>
</div>
<br/>
This Is Next Lay Out

<div class="header">
<h1>header</h1>
</div>
<div class="body">
<div class="a1">
  <div style="width:100%; height:50%; background:#ff8800;">1</div>
  <div style="width:100%; height:50%; background:#ffff00;">2</div>
  </div>
  <div class="a2">3</div>
  <div class="a3">4</div>
  <div class="a4">5</div>
</div>

试一试

【讨论】:

  • 谢谢,但这不是响应式的。我需要相同的布局才能在两种情况下工作,具体取决于屏幕宽度。