This forum is now read-only. Please use our new forums! Go to forums

0 points
Submitted by Matt Saba
almost 9 years

How to Center my text in CSS Vertically

Hey there,

I’m trying to align my text vertically in CSS, how do you go about doing that?

I’ve already tried this: vertical-align: middle but it didn’t do the trick… what gives?

Cheers

Answer 53d814538c1ccc00aa000364

1 vote

Permalink

There are a number of possible ways to do this. In cases where the height is relatively fixed, we can use line-height. In lesson 1 of 6 you can experiment free of charge since there is no SCT for that lesson. Save your work so you can refer back to it.

Just inside the body tag paste in this HTML:

<ul class="menu">
    <li><a>Home</a></li>
    <li><a>About</a></li>
    <li><a>Contact</a></li>
    <li><a>Info</a></li>
</ul>

Now in the stylesheet.css tab add this CSS to the bottom of the sheet:

ul.menu {
    margin: 0 auto;
    text-align: center;
}
ul.menu li {
    display: inline-block;
    height: 2em;
}
ul.menu a {
    display: block;
    width: 5em;
    line-height: 2em;
    background-color: #fed;
    border-radius: 5px;
}
ul.menu a:hover {
    color: #fed;
    background-color: #abc;
    cursor: pointer;
}

If you adjust line-height to 3em you will see how the text shifts to remained vertically centered. Try 4em, then 5em. This is just one method. I like it because it is simple and fits the purpose.

On a larger scale, one may need to use top and bottom padding in a container element. This is clunkier, but can be made to work in the right situations. Purpose, dimensions and amount of content will be determining factors.

points
Submitted by Roy
almost 9 years