0

I often use line-height for vertical centering the text within a inline-element.

I have made this demo:

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
}

.my-element {
  line-height: 48px;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>

Works fine. The text is exact vertically centered within the grey bar.

But the Problem with this approach is: I got to use the height of the parent-element and put it fixed in there.

Is there a better, a more dynamic approach, when using this pattern.

So that it doesn't become broken when the height of the parent-element changes.

cluster1
  • 4,968
  • 6
  • 32
  • 49
  • Possible duplicate of [How to vertically center text with CSS?](http://stackoverflow.com/questions/8865458/how-to-vertically-center-text-with-css) and [Vertically align text in a div](http://stackoverflow.com/questions/2939914/vertically-align-text-in-a-div) and others found by searching SO. – Rob Apr 09 '17 at 11:05

3 Answers3

1

Just remove the height functions. After doing this there will be no space between the span and div. So you add a padding. padding: 10px 0px 10px 0px; Which I have used below, you could even use something like padding: 10px; to be less specific.

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  padding: 10px 0px 10px 0px;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>
1

You can use Flexbox and set align-items: center and justify-content: center for both vertical and horizontal center.

section {
  background-color: lightGrey;
}

#wrap {
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

You can use transform: translate, and the dupe link has many more ways

body,
section {
  width: 100%;
}

section {
  background-color: lightGrey;
}

#wrap {
  position: relative;
  margin: 30px auto;
  width: 100%;
  max-width: 800px;
  text-align: center;
  height: 48px;
}

.my-element {
  position: relative;
  display: inline-block;
  top: 50%;
  transform: translateY(-50%);
}
<section>
  <div id="wrap">
    <span class="my-element">My element</span>
  </div>
</section>
Asons
  • 84,923
  • 12
  • 110
  • 165