使用flex对齐多个元素

时间:2017-01-11 09:21:56

标签: html css css3 flexbox

我想用flexbox做类似的事情:

enter image description here

.wrap {
  display: flex;
  flex-wrap: wrap;
}
.elem1 {
  width: 20%;
  height: 100px;
  border: 1px solid red;
}
.elem2, .elem3 {
  width: 75%;
  border: 1px solid red;
}
<div class="wrap">
  <div class="elem1">1</div>
  <div class="elem2">2</div>
  <div class="elem3">3</div>
</div>

JSFIDDLE

2 个答案:

答案 0 :(得分:3)

切换到flex-direction: column

添加flex-wrap: wrap

定义容器的高度(以便flex项知道包装的位置)。

第1列将消耗第一列中的所有空格,强制将以下框包装到新列。

无法更改HTML。

.wrap {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;         /* NEW */
  height: 100px;                  /* NEW */
  justify-content: space-between; /* NEW */
}
.elem1 {
  width: 20%;
  flex-basis: 100%;               /* NEW */
  border: 1px solid red;
}
.elem2,
.elem3 {
  width: 75%;
  flex-basis: 40%;                /* NEW */
  border: 1px solid red;
}
<div class="wrap">
  <div class="elem1">1</div>
  <div class="elem2">2</div>
  <div class="elem3">3</div>
</div>

答案 1 :(得分:0)

这样的事情可能(根据需要调整值):

1。使用你的身高(100px)&amp; width s(20%&amp; 75%):

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
html,
body {
  height: 100%;
  width: 100%;
}
.wrap {
  height: 100px;
  display: flex;
  flex-flow: row wrap;
}
.row {
  width: 75%;
  display: flex;
  flex-flow: column wrap;
}
.elem1 {
  width: 20%;
  border: 1px solid lightgray;
}
.elem2 {
  height: 50%;
  border: 1px solid lightgray;
  flex: 1;
  margin: 10px;
}
.elem3 {
  height: 50%;
  border: 1px solid lightgray;
  flex: 1;
  margin: 10px;
}
<div class="wrap">
  <div class="elem1">1</div>
  <div class="row">
    <div class="elem2">2</div>
    <div class="elem3">3</div>
  </div>
</div>

2。全宽&amp;高度选项:

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}
html,
body {
  height: 100%;
  width: 100%;
}
.wrap {
  height: 100%;
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
}
.row {
  width: 80%;
  display: flex;
  flex-flow: column wrap;
}
.elem1 {
  width: 20%;
  border: 1px solid lightgray;
}
.elem2 {
  height: 50%;
  border: 1px solid lightgray;
  flex: 1;
}
.elem3 {
  height: 50%;
  border: 1px solid lightgray;
  flex: 1;
}
<div class="wrap">
  <div class="elem1">1</div>
  <div class="row">
    <div class="elem2">2</div>
    <div class="elem3">3</div>
  </div>
</div>