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.
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.
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.
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.
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
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 div
s 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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With