Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inline-Block inside Inline-block Invisible Margin

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.

like image 521
Maxwell s.c Avatar asked Jun 06 '26 14:06

Maxwell s.c


1 Answers

Each inline or inline-block element on its own line (like your :after) element, will behave like a line of text, and is therefore subject to the line-height, vertical alignment and baseline of whatever font and font-size you've set on the parent (24px).

While it requires an extra element, your initial example solution of wrapping the text in its own element, applying a 0 font-size to parent, and applying the 24px font-size only to the text element (and therefore to that first line only), is the best solution if you don't want to resort to hacks such as negative margins or negative line-heights.

This is a summary of typographic CSS properties as they would apply to inline or inline-block elements: https://iamvdo.me/en/blog/css-font-metrics-line-height-and-vertical-align

like image 117
Patrick Kunka Avatar answered Jun 09 '26 06:06

Patrick Kunka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!