2

I'm following this SO Answer to vertically align a div's contents that has float: left styling:

.main {
  height: 85px;
}

.child_1,
.child_2 {
  float: left;
  width: 8rem;
}
<div class="main">
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_1">
      Some long text is put here
    </div>
  </div>
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_2">
      22
    </div>
  </div>
</div>

But, it doesn't vertically align as per the height of the wrapper div main. What is wrong in the code?

kukkuz
  • 41,512
  • 6
  • 59
  • 95
Abhi
  • 4,123
  • 6
  • 45
  • 77

2 Answers2

4

If you add

display: flex;
align-items: center;

to .main class, it should work.

.main {
  height: 85px;
  background-color: #f00;
  /*position: absolute;*/
  /*top: 2rem;*/
  display: flex;
  align-items: center;
}

.child_1,
.child_2 {
  float: left;
  width: 8rem;
}
<div class="main">
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_1">
      Some long text is put here
    </div>
  </div>
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_2">
      22
    </div>
  </div>
</div>
Boky
  • 11,554
  • 28
  • 93
  • 163
4

In the linked question, you can see that the line box aligns itself, but not exactly with the main - try setting a height for the main and you'll see.

You've height set for the main here and that makes all the difference. For this you can use a psuedo element to center:

.main:after{
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}

See demo below:

.main {
  height: 85px;  
  border: 1px solid;
}

.child_1,
.child_2 {
  float: left;
}

.main:after{
  display: inline-block;
  vertical-align: middle;
  height: 100%;
  content: '';
}
<div class="main">
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_1">
      Some long text is put here
    </div>
  </div>
  <div style="display: inline-block;vertical-align: middle;">
    <div class="child_2">
      22
    </div>
  </div>
</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95