Flexbox-在多个列中对齐项目基线

时间:2019-06-10 19:04:37

标签: html css flexbox

有没有一种方法可以使列中的行与基线对齐?

在示例中,只有“ A”正确对齐。我想要的是使基线也具有相同的html结构的“ B”和“ C”。

https://jsfiddle.net/hxzuar7f/

我知道类似的东西会起作用

<div class="row">
  <div class="column">A</div>
  <div class="column">A</div>
  <div class="column">A</div>
</div>
<div class="row">
  <div class="column">B</div>
  <div class="column">B</div>
  <div class="column">B</div>
</div>

但是我想做这个

<div class="container">
    <div class="element">
        <div class="row">
            <h1>A</h1>
        </div>
        <div class="row">
            <div>B</div>
        </div>
        <div class="row">
            <div>C</div>
        </div>
    </div>
    <div class="element">
        <div class="row">
            <div>A</div>
        </div>
        <div class="row">
            <div>B</div>
        </div>
    </div>
</div>

(绿线正确,红线错误)

这是我想用CSS实现的: this is what I want to achieve with CSS

这就是我现在得到的: this is what I got now

1 个答案:

答案 0 :(得分:0)

解决方案1:→行

那是因为您的元素在列而不是内联中。当元素水平对齐时,align-items: baseline属性起作用。因此,达到flex-direction: row这样的效果是最好的方法:

h1, h3, div {
  display: flex;
  align-items: baseline;
  flex-direction: row;
  box-sizing: border-box;
}

.element {
  display: flex;
  padding: 20px;
  width: 200px;
  justify-content: space-between;
}

.container {
  width: 100%;
  display: flex;
  flex-direction: column;
}

.row {
  display: flex;
}
<div class="container">
    <div class="element">
      <div class="row">
        <h1>A</h1>
      </div>
      <div class="row">
        <div>B</div>
      </div>
      <div class="row">
        <div>C</div>
      </div>
    </div>
    <div class="element">  
      <div class="row">
        <div>A</div>
      </div>
      <div class="row">
        <div>B</div>
      </div>
    </div>
    <div class="element">
      <div class="row">
        <div>A</div>
      </div>
      <div class="row">
        <h3>B</h3>
      </div>
      <div class="row">
        <div>C</div>
      </div>
    </div>
</div>


解决方案2:添加一个margin-bottom

如果您确实想将元素保留在列中,则需要为每个margin-bottom元素添加一个row。但是删除h1h2的填充。像这样:

h1, h3, div {
  display: flex;
  align-items: baseline;
  flex-direction: row;
  box-sizing: border-box;
  margin:0;
}

.element {
  display: flex;
  padding: 20px;
  width: 200px;
  flex-direction: column;
}

.container {
  flex-direction: row;
}

.row {
  margin-bottom: 40px;
  display: flex;
}
<div class="container">
    <div class="element">
      <div class="row">
        <h1>A</h1>
      </div>
      <div class="row">
        <div>B</div>
      </div>
      <div class="row">
        <div>C</div>
      </div>
    </div>
    <div class="element">  
      <div class="row">
        <div>A</div>
      </div>
      <div class="row">
        <div>B</div>
      </div>
    </div>
    <div class="element">
      <div class="row">
        <div>A</div>
      </div>
      <div class="row">
        <h3>B</h3>
      </div>
      <div class="row">
        <div>C</div>
      </div>
    </div>
</div>