Ethan Leyden
Ethan Leyden

Reputation: 298

Center an element vertically HTML

I am trying to vertically center a header element in my nav element, and I tried to calculate the height of the <h1> using this CSS:

.navbar {
    display: table;
    width:90%;
    height: 3em;
    background-color: #7f8c8d;
    border-radius: 10px;
    .nav-title {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
    .nav-dropdown {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }
}

It worked, and I don't understand how. I was also wondering if there were any better ways to center an element vertically. TL;DR: How does this work? What are other ways to accomplish what this code accomplishes.

Upvotes: 0

Views: 64

Answers (2)

paradizzee
paradizzee

Reputation: 111

See it as a table, you create a table cell of your .nav-title. You are able to vertically align them, that's how it works.

Are there any easy ways to center vertically? A few, but in a lot of occassions some of them don't work.

Here is one:

    .element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Upvotes: 1

Tims
Tims

Reputation: 2007

This works because you are setting the display to table and table-cell. Table cells natively allow for vertical centering.

Without using tables you still have lots of other options (though none of them seem to be as simple).

CSS-Tricks has a handy writeup of various centering methods.

Upvotes: 1

Related Questions