Follow this blog

Wednesday, October 31, 2012

Center a HTML element

How to center div element? This is a question that ask many HTML beginners.

And this is not only question about centering. Frequently people do not know how to center text or button inside div element or button , how to center image inside div element, how to center div block on the screen and many other variations...

In this article we will try to give simple instructions with samples how to make some most common HTML centering.


Center a text inside div:


This text is centered inside div

Code for centering text inside div

<div align=center>This text is centered inside div</div>

So, to div element is added align attribute with value center and we get centered text inside div element.


Center HTML button element inside div element:



Code for centering button element in div

<div align=center><input id="Button1" type="button" value="Centered button" />
</div>

Button HTML element is centered inside div element similar like in previous example. Align is set to center.


Center an image inside div element


Code for centering image in div element:

<div align=center> 
 <img alt="" src="http://www.userinterfaceicons.com/80x80/redo.png" 
            style="height: 85px; width: 198px" id="image" />
</div>

Image is in div element which have align attribute set to center.


Center a div block on screen:

Div block is centered but text is on the left side

Code for centering div block on screen:

<div style="width: 280px; margin-right:auto; margin-left:auto" >
Div block is centered but text is on the left side
</div>

This div is center on the screen but text inside div is not. Div is centered on screen or in some other HTML element by setting margin-right and margin-left attributes to auto.


Center a div block and text inside it

Div block is centered and text is
centered

Code for centered div element with centered text inside it:

<div style="width: 280px; margin-right:auto; margin-left:auto;" align=center >
Div block is centered and text is centered
</div>

This is like previous example. Only difference is that align attribute is set to center.


1 comment:

Oregon said...

Very well explained. Sometimes, for just centering text I use text-align=center, too. Good now we almost forgot those < center > tag :)