Inline-Block inside Inline-block Invisible Margin

Viewed 2333

See this pen for an example and one solution: https://codepen.io/MaxViewUp/pen/YrXzRG

I have an inline title that will have width acording to the text width, and i have an :after inside it (or an div if you want) with inline-block too and width of 70%. I use inline-blocks because i have 3 variations of this title (left, right and center), so i just change the text direction to change the title.

The problem: The inline-block element is having an strange invisible "margin-top" from the text. I want to know why this is happening and an better solution. I think is something related to the font-size (bigger font size bigger spacing) but i'm not sure.

Solutions until now:

  • font-size: 0 - not an good solution because it mess the HTML;
  • display:block or float:left on the :after - not an good solution because text alignment will not affect it;

if anyone know exactly why this happens, please explain it.

CSS code:

.main-title {
  display: inline-block;
  font-size: 24px;
}
.main-title:after {
  content: '';
  display: inline-block;
  width: 70%;
  height: 2px;
  background: green;
}
.main-title-wrapper {
  margin: 20px 0;
}
.main-title-wrapper.right {
  text-align: right;
}
.main-title-wrapper.center {
  text-align: center;
}

NOTE I want to solve the problem but i really need is the reason this is happening (documentation, etc). Thanks for helping.

5 Answers
Related