Learn to use standards compliant, cross browser CSS code to center elements. Author:Ashley Stevens Difficulty: 2/10
Centering Pixel-Sized Elements with CSS
CSS (cascading style sheet) is a great technology for use with web design. It is fast loading and supports a vast range of web browsers, looking good on them all at any resolutions (well, unless you’re speaking mobile phone or PDA's where problems can occur) if you program it properly. Face it; tables were never made for design, they are great for tabular content and occasional layout sculpture, but shouldn't’t generally be used for design.
A major issue facing designers looking to make that leap of faith to CSS based design is its lack of support for element alignment (left, center and right). If you are using percentages for your dimensions then it is easy to center objects, the width of the screen is 100%; therefore you must space your element half of the difference between its width and 100% from the left.
But every person who knows anything about graphics knows that they cannot be sized in percent! Nope, when you’re working with images then your only choice is good old pixels…
So let’s use an example; I have an image with the dimensions 250px*100px (px is shorthand for pixels, and used in CSS). I want to center my image so firstly I insert it into my web page using the following code:
You may have noticed, that I have added a property to the image you may not expect; “class="piccy"”. This gives the image the properties we are about to define into our CSS code…
We are using a class because it is not correct to give an image an ID, but the same method can be applied to ID’s too.
Without further ado…
It looks a little complex just to center an image at first, but once you discover the way each part works you realize just how simple it is. Firstly we position the image as absolute so that it goes precisely where we tell it to go, and then we define the dimensions of it.
Now for the clever part, we align it 50% from the left and then give it a left margin of minus half the width of the image. This works because with left 50%, the left hand side of the image is positioned exactly 50% away from the left. We then move it left of this position by half of the images width. The result is an image exactly centered.
Think it over, it’s hard to grasp at first but is pretty logical once you understand. Here is an example demo:
Remember, this can also be modified to align vertically center. Just change the left value to ‘top’ and the margin left to ‘margin-top’. This concludes this tutorial and I hope you use CSS as your advantage in web design.