显示前两个弹性项目,它们彼此居中并顶部对齐

时间:2019-03-21 17:29:33

标签: html css css3 flexbox alignment

我正在尝试将前两个图块彼此居中对齐(带有紫色边框的图块),并使所有三个方框顶部对齐。我已经使用display: inline-flex实现了这一目标,但仅使用display: flex是否有可能获得相同的结果?

Fiddle

.container {
  font-size: 0;
  box-sizing: border-box;
}

.blocks {
  display: inline-flex;
}

.blocks-left {
  align-items: center;
  width: 66%;
  vertical-align: top;
  border: 2px solid purple;
}

.blocks-right {
  width: 33%;
}

.block {
  width: 100%;
}

#block-1 {
  background: red;
  height: 100px;
}

#block-2 {
  background: blue;
  height: 200px;
}

#block-3 {
  background: green;
  height: 400px;
}
<div class="container">
  <div class="blocks blocks-left">
    <div id="block-1" class="block"></div>
    <div id="block-2" class="block"></div>
  </div>
  <div class="blocks blocks-right">
   <div id="block-3" class="block"></div>
   </div>
</div> 

2 个答案:

答案 0 :(得分:1)

如果要将blocks更改为 block-level display: flex,则将container设置为 flexbox可以得到相同的结果并将align-self: flex-start添加到blocks-left元素-请参见下面的演示:

.container {
  font-size: 0;
  box-sizing: border-box;
  display: flex; /* added */
}

.blocks {
  display: flex; /* now flex instead of inline-flex */
}

.blocks-left {
  align-items: center;
  align-self: flex-start; /* added */
  width: 66%;
  vertical-align: top;
  border: 2px solid purple;
}

.blocks-right {
  width: 33%;
}

.block {
  width: 100%;
}

#block-1 {
  background: red;
  height: 100px;
}

#block-2 {
  background: blue;
  height: 200px;
}

#block-3 {
  background: green;
  height: 400px;
}
<div class="container">
  <div class="blocks blocks-left">
    <div id="block-1" class="block"></div>
    <div id="block-2" class="block"></div>
  </div>
  <div class="blocks blocks-right">
   <div id="block-3" class="block"></div>
   </div>
</div>

答案 1 :(得分:0)

display: flexalign-items: flex-start一起设置为主容器。这是您需要的吗?

.container {
  font-size: 0;
  box-sizing: border-box;
  display: flex;
  align-items: flex-start;
}

.blocks {
  display: flex;
}

.blocks-left {
  align-items: center;
  width: 66%;
  vertical-align: top;
  border: 2px solid purple;
}

.blocks-right {
  width: 33%;
}

.block {
  width: 100%;
}

#block-1 {
  background: red;
  height: 100px;
}

#block-2 {
  background: blue;
  height: 200px;
}

#block-3 {
  background: green;
  height: 400px;
}
<div class="container">
  <div class="blocks blocks-left">
    <div id="block-1" class="block"></div>
    <div id="block-2" class="block"></div>
  </div>
  <div class="blocks blocks-right">
    <div id="block-3" class="block"></div>
  </div>
</div>