Centering Elements with CSS
There are very few references for using CSS to center elements, so I hope this helps you understand some fundamental principles of Cascading Style Sheets. You can use the "align" attribute on some HTML elements or revert to the ancient center tag to center your web page content, but these are long-depreciated and obsolete website design techniques that have limitations that you should avoid.
So let's explore a couple of methods of centering elements with CSS. The best
approach is to use set the appropriate horizontal margin settings, left and/or right, to "auto"
on any block-level element to be centered, and using "text-align:center" to center inline
elements within a block-level element. Use the "View Source" command in your browser to
view the source HTML for this page. The critical CSS rules are all in the head section, and
so look for the div tag in the HTML code with the class attribute of "cellContainer".
This text is contained in a pair of nested divs: an inner div (class 'cellBody' in this document) and an outer container div (class 'cellContainer'). The outer div is set to a width of 100% which it inherits from the parent containing element. The parent in this case is the div 'bodyContent', but it could be any other block level element within your document. The inner div that encloses the content to be centered has its width set to 75% of the width of its parent block-level element. The concept of the containing element is one you need to absorb when dealing with CSS because, after all, it's the "cascading" capabilities of CSS that are so fundamental.
To center the image below within the already-centered containing div that holds this text block, I enclosed the inline element img with a paragraph tag, and used "text-align:center" on the p tag.
But the key is that the margin of the inner div has its left and right settings set to "auto" which automatically adjusts to the size of the viewport as the window is resized, keeping the element(s) contained in the inner div perfectly centered. You can use this technique anywhere on your page, since it does not rely on absolute positioning or nested table tags that can get difficult to maintain and edit as your webpage design changes.
Vertical Centering with CSS
This is the outer containing div. It needs to have it's position set to either relative or absolute in order to give the content to be centered vertically a reference point because it relies on absolute positioning.
Content to be centered vertically with CSS
The Smashing Magazine website recently published an in-depth article on horizontal and vertical centering with CSS. The vertical centering method the author uses is particularly well-done. Check it out!
This page was last modified on December 09, 2015