Jump to content
JustRob

Why is it so complicated to position text with CSS

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

Share this post


Link to post
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.

Share this post


Link to post
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;
}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...