seminolas seminolas - 1 month ago 17
CSS Question

Align single and double-line containers

I have a header row where some of the header names are too long to fit on one line and have to be split. The headers are fixed height, sufficient for two lines. The text should be vertically centered.

Something like:



.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>





I can't figure out how to align all those headers correctly. Setting
line-height
to 40px makes the second header double-height; setting height to 40px throws them out of alignment.

Thanks!

Answer

So this is what I changed in your code:

  1. Add vertical-align: middle to align the pills

  2. Give line-height same as height for the pills other than split using the not selector:

    .pill:not(.split) {
      line-height: 40px;
    }
    
  3. In smaller displays the menu will wrap - so use float and clear them too.

Let me know your thoughts on this, thanks!

.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>