Andrew Pallant

Software and Web Developer

Tuesday, December 29, 2009

 

HTML Centering DIV Tag ( DIV Element )

The easiest way without JavaScript to center a DIV tag is to use a style tag or css that resembles the following.


style='padding:5px;width: 400px;height:200px; margin-top:-100px; margin-left:-200px; left:50%;top:50%; border:outset 1px #ccff99; background-color:#ccff99;position:absolute;font-weight:normal;'



Sample Image

Comments:
I have a couple of questions about this post:

1. Is this supposed to be defined at the HTML element level? Isn't the non-intrusive approach better? (defining a class in a separate .css file and assigning a class to the HTML element, for example)

2. What do the background-color, border, and font-weight attributes have to do with positioning an element?

3. Will it work the same when the user's screen resolution is 1280x1024 and when it is 1920x1080?
 
1. You can define in a CSS or style attribute in the header or in-line on the element. I would always suggest using it in CSS, for demonstration purposes I did not. You should always use the CSS file wherever possible, as it is easier for branding and templating. Take my example and throw it into a CSS file.

2. Nothing, just supports the pretty picture that I posted for demonstration purposes.

3. It will always work no matter the browser, OS or screen resolution. - have not seen it fail yet. - I suppose there is always a first.
 
Post a Comment





<< Home