Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center a H1 tag inside a DIV

I have the following DIV inside a body tag:

<div id="AlertDiv"><h1>Yes</h1></div> 

And these are their CSS classes:

#AlertDiv {     position:absolute;     height: 51px;     left: 365px;     top: 198px;     width: 62px;     background-color:black;     color:white; }  #AlertDiv h1{     margin:auto;     vertical-align:middle; } 

How can I align vertically and horizontally H1 inside DIV?

AlertDiv will be bigger than H1.

like image 400
VansFannel Avatar asked Jun 06 '11 16:06

VansFannel


People also ask

How do I center a header within a div?

If you need to use CSS to center text within an element like a div, header or paragraph you can use the CSS text-align property. Setting the text-align property to center is the most common way to horizontally align text using CSS.

How do you center an A in a div?

To horizontally center a block element (like <div>), use margin: auto; Setting the width of the element will prevent it from stretching out to the edges of its container.

How do you center a heading in CSS?

For example, say you want the headings centered on a page, but the paragraphs to be left aligned. Then you'd use the type selector h2 and set the text-align property to center.


2 Answers

You can add line-height:51px to #AlertDiv h1 if you know it's only ever going to be one line. Also add text-align:center to #AlertDiv.

#AlertDiv {     top:198px;     left:365px;     width:62px;     height:51px;     color:white;     position:absolute;     text-align:center;     background-color:black; }  #AlertDiv h1 {     margin:auto;     line-height:51px;     vertical-align:middle; } 

The demo below also uses negative margins to keep the #AlertDiv centered on both axis, even when the window is resized.

Demo: jsfiddle.net/KaXY5

like image 96
Marcel Avatar answered Oct 10 '22 06:10

Marcel


There is a new way using transforms. Apply this to the element to centre. It nudges down by half the container height and then 'corrects' by half the element height.

position: relative; top: 50%; transform: translateY(-50%); -webkit-transform: translateY(-50%); -ms-transform: translateY(-50%); 

It works most of the time. I did have a problem where a div was in a div in a li. The list item had a height set and the outer divs made up 3 columns (Foundation). The 2nd and 3rd column divs contained images, and they centered just fine with this technique, however the heading in the first column needed a wrapping div with an explicit height set.

Now, does anyone know if the CSS people are working on a way to align stuff, like, easily? Seeing that its 2014 and even some of my friends are regularly using the internet, I wondered if anyone had considered that centering would be a useful styling feature yet. Just us then?

like image 26
Luke Puplett Avatar answered Oct 10 '22 05:10

Luke Puplett