对齐单行和双行容器



我有一个标题行,其中一些标题名称太长,不能放在一行中,必须拆分。头是固定高度,足够两行。文本应该垂直居中。

类似:

.container {
  width: 100%;
  height: 40px;
}
.pill {
  display: inline-block;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
}
<div class="container">
  <div class="pill">
    Header One
  </div>
  <div class="pill split">
    Header
    <br/>Two
  </div>
  <div class="pill">
    Header Three
  </div>
</div>

我不知道如何正确对齐所有这些标题。将line-height设置为40px使第二页眉双倍高度;将高度设置为40px会使它们偏离对齐。

谢谢!

这就是我在你的代码中所做的更改:

  1. 添加vertical-align: middle对齐pill s

  2. 使用not选择器为pill s (split除外)赋予line-height相同的高度:

    .pill:not(.split) {
      line-height: 40px;
    }
    
  3. 在较小的显示器中,菜单将自动换行-因此也使用floatclear

让我知道你的想法,谢谢!

.container {
  width: 100%;
  height: 40px;
}
.pill {
  display: inline-block;
  vertical-align: middle;
  float: left;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
}
.pill:not(.split) {
  line-height: 40px;
}
.pill:after{
  content: '';
  display: block;
  clear: both;
}
<div class="container">
  <div class="pill">
    Header One
  </div>
  <div class="pill split">
    Header
    <br/>Two
  </div>
  <div class="pill">
    Header Three
  </div>
</div>

Flexbox可以做到:

.container {
  width: 100%;
  height: 40px;
  display: flex;
}
.pill {
  display: flex;
  flex: 0 0 30%;
  margin: 0 1%;
  justify-content: center;
  align-items: center;
  text-align: center;
  background-color: red;
  height: 40px;
}
<div class="container">
  <div class="pill">
    Header One
  </div>
  <div class="pill split">
    LONG HEADER TEXT GOES HERE
  </div>
  <div class="pill">
    Header Three
  </div>
</div>

一个选择是改变元素并排设置的方式,所以代替inline-block:

<标题>表格单元

.container {
  width: 100%;
  height: 40px;
}
.pill {
  padding:10px;
  border:1px solid white;
  display: table-cell;
  width: 33%;
  background-color: red;
  text-align: center;
  height: 40px;
  vertical-align:middle;
}
<div class="container">
  <div class="pill">
    Header One
  </div>
  <div class="pill">
    Header
    <br/>Two
  </div>
  <div class="pill">
    Header Three
  </div>
</div>

添加以下内容到您的.pill css:

vertical-align:middle;

下面是一个例子

最新更新