Jump to content

Why is it so complicated to position text with CSS


JustRob

Recommended Posts

I wanted to make a basic example website to use while following the HTML tutorial, so I started out with a background color and a header block of 200px high and 800px wide. I put some text in the header which I wanted to center horizontally and vertically. Horizontally is easy enough, but when I googled how to do it vertically I only found complicated answers. Then I thought maybe I'd position the text elsewhere, like in the bottom left of the header. Turns out that's even more complicated.

 

Why is this such a pain? Why can't it be as simple as one line of CSS?

Edited by JustRob
Link to comment
Share on other sites

The reason it is complicated to position text using CSS is because there is a range of browsers and screen resolutions which the code may be rendered on. So the code must be written in such a way as to address all of these possibilities. In your example, centering a block vertically can only be done when you have a fixed screen height of some known value. But since one can generally scroll down a page as long as there is something to display, there is no known bottom. What I would do is provide a margin-top:20px; attribute to your body tag, or, if your text is contained in a DIV tag, provide that div tag with a margin-top value.

Link to comment
Share on other sites

There are ways to vertically center elements, but the right solution depends on the case.

 

In the case of your header, if you set the line-height to 200px the text will be centered, however, if the text wraps it will be outside of the box.

 

If you need wrapping text, wrap it inside an inline-block and set the line-height of that block to "normal"

<header class="main">
  <h1>Vertically Centered <br> Wrapping Text </h1>
</header>

.main {
  width: 800px;
  height: 200px;
  line-height: 200px;
  text-align: center;
}

.main h1 {
  display: inline-block;
  vertical-align: center;
line-height: normal;
}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...