Roland Soós
Roland Soós

Reputation: 3280

inline-block vertical centering issue

I have the following simple code snippet. It is taken out from my application where .a1 is a container button, which has an icon. The icon should be vertically middle aligned to the parents line-height/height, but it is shifted with 1px from top. Could you explain me why this is the behavior? Is there any solution?

.a1 {
  display: inline-block;
  width: 28px;
  line-height: 28px;
  background-color: #000;
  text-align: center;
  vertical-align: middle;
}
.i {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #f00;
  vertical-align: middle;
}
<div class="a1"><i class="i"></i>
</div>

Upvotes: 2

Views: 51

Answers (4)

web-tiki
web-tiki

Reputation: 103750

Why?

Because inline-block elements render with "white-space". You can see this in this demo where no height/width is set on the parent element.

When you use vertical-align:middle; the "white space" is rendered before the element (on top) (black line in the demo). This space moves the child element down and therefore it doesn't appear verticaly centered.

how to fix :

You can use display:block; and calculate the margin to apply to the child element so it centers verticaly and horzontaly.

You can also take a look at this question which talks about white space and ways to avoid them.

Upvotes: 1

Roland So&#243;s
Roland So&#243;s

Reputation: 3280

Well, it seems like font-size:0; for .a1 seems also a fix for such issue.

.a1 {
  display: inline-block;
  width: 28px;
  line-height: 28px;
  background-color: #000;
  text-align: center;
  vertical-align: middle;
  font-size: 0;
}
.i {
  display: inline-block;
  width: 16px;
  height: 16px;
  background-color: #f00;
  vertical-align: middle;
}
<div class="a1"><i class="i"></i>
</div>

Upvotes: 1

user3722785
user3722785

Reputation: 216

.a1 {
  display: inline-block;
  background-color: #000;
}
.i {
  display: block;
  width: 16px;
  height: 16px;
  margin: 6px 6px;
  background-color: #f00

Upvotes: 0

Jason Williams
Jason Williams

Reputation: 2860

.a1 {
  display: inline-block;
  background-color: #000;
}
.i {
  display: block;
  width: 16px;
  height: 16px;
  margin: 6px 6px;
  background-color: #f00;
}
<div class="a1"><i class="i"></i>
</div>

Upvotes: 0

Related Questions