Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Center vertically a unknown height text in a unknown height div

Center vertically a unknown height text in a unknown height div

Problem

I know this is a common issue, and I've already asked a similar one. But I could not find the solution this time. I am trying to vertically center a text which can have different Height in a DIV which can have different height. And I am trying to solve this only with CSS, without touching the HTML.

Example : http://jsfiddle.net/F8TtE/

 

Title

hello guys

My goal is to have the text centered vertically and horizontally whatever its size.

Problem courtesy of: Damien

Solution

Here it is :

#test {
    text-align:center;
}
#test::before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
#sumup {
    display: inline-block;
    vertical-align: middle;
}
#test {
    height : 180px;
    text-align:center;
    background: yellow;
}

#sumup {
   	background-color: #123456;
}

#test:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
  }
  #sumup {
    display: inline-block;
    vertical-align: middle;
  }

Title

hello guys

EDIT: It's now 2015 and thankfully the web changes. Assuming you don't support obsolete browsers, it's usually simpler and cleaner to vertically center elements with the Flex model.

#test {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
#test {
    height : 180px;
    background: yellow;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}

#sumup {
   	background-color: #123456;
}

Title

hello guys
Solution courtesy of: Denys Séguret

Discussion

View additional discussion.



This post first appeared on CSS3 Recipes - The Solution To All Your Style Problems, please read the originial post: here

Share the post

Center vertically a unknown height text in a unknown height div

×

Subscribe to Css3 Recipes - The Solution To All Your Style Problems

Get updates delivered right to your inbox!

Thank you for your subscription

×