2

I've recently seen in Google's Material Design the use of :before's pseudo element to generate vertical space prior to dialog headings.

<h2>
  :before { content:''; height: 40px; width:0; display:inline-block; vertical-align: 0 }
  Some Text
</h2>

Instead of padding/margin-top or a wrapper with necessary space. I'm curious as to what the reasoning may have been behind doing this and if there is a benefit to this approach?

  /* as seen on mdc's alertdialog headings: https://material-components.github.io/material-components-web-catalog/#/component/dialog */

.title {
  /* prefixes & repeat styles removed for easier reading */
  line-height: normal;
  font-family: Roboto, sans-serif;
  -moz-osx-font-smoothing: grayscale;
  -webkit-font-smoothing: antialiased;
  font-size: 1.25rem;
  line-height: 2rem;
  font-weight: 500;
  letter-spacing: .0125em;
  text-decoration: inherit; /* none */
  text-transform: inherit; /* none */
  display: block;
  position: relative;
  flex-shrink: 0;
  box-sizing: border-box;
  margin: 0;
  padding: 0 24px 9px;
  border-bottom: 1px solid transparent;
}

.title:before{
  content:'';
  height:40px;
  width:0;
  display:inline-block; /* is left of the element */
  vertical-align: 0; /* baseline */
}
<h2 class="title">Heading</h2>
darcher
  • 3,052
  • 3
  • 24
  • 29
  • 1
    I guess it has something to do with collapsing margins. https://stackoverflow.com/questions/1828804/how-do-i-uncollapse-a-margin https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing – SuperDJ Dec 07 '18 at 21:20
  • @SuperDJ Increasing the height of the element to create space seems more like an attempt to imitate *padding* (which doesn't suffer from margin collapse), so I'd be surprised if that were the case. Unless it was coupled with the idea of using `border-box: box-sizing;` globally, which is entirely possible. – Tyler Roper Dec 07 '18 at 21:22
  • 1
    @TylerRoper even box-sizing won't play a role here unless we explicitely set a height – Temani Afif Dec 07 '18 at 21:30
  • @TemaniAfif You're correct. The header height would expand due to padding regardless of `box-sizing`. – Tyler Roper Dec 07 '18 at 21:50
  • It looks like it's using it as @SuperDJ said, the 1.25rem font size is 20px, making the height of the `:before` 40px, this matches the 2rem line-height. either way, there's about an 8-9 pixel space above the heading, which matches the 9px bottom padding. – darcher Dec 10 '18 at 16:05

0 Answers0