The top 10 things you've always wanted to do in CSS

Published on October 4th 2007.

Modified on July 26th 2010.

Horizontally centre an element

As you most probably know, the align="center" property has been depreceated for a good long while (since HTML 4). To centre a block element we use CSS to alter its margins.

Block Elements

		
		margin:0 auto;
		

By using margin:0 auto, we are creating equal margins on both the left and right sides of our block element, thus pushing it to the centre of the screen (this is the same as using margin-right:auto; margin-left:auto). Why does this create a centering effect? Well, the W3C Visual Formatting Model say that if both margin-left and margin-right are set to auto, their values will become equal, thus causing the element to be horizontally aligned.

Inline Elements

		
        display:block;
        margin:0 auto;
		

Inline elements will not centre with margin:0 auto alone, as it isn't in their nature. An inline element will not break the flow of a page, therefore, bare of CSS, no matter what you put on its margins, it will not move. To get around this, we must convert our inline elements into block elements, by using display:block.

Note that margin:0 auto will not work on inline elements if you have anything above the doctype on your page, in IE6.

A div horizontally centred on screen

A div horizontally centred on screen

Float block elements next to each other

Floating block elements next to each other requires using the CSS float property. It has four values: left, right, none and inherit (the latter of which isn't supported by IE versions below 8).

Floating items left

CSS Code:

       #floatExCont {
            float:left;
            overflow:auto;
            background-color:#09C;
            border:1px solid #039;
        }
                    
        #floatExLeftOne, #floatExLeftTwo {
            float:left;
            width:200px;
            height:200px;                
        }
        
        #floatExLeftOne {
            background-color:#696;
        }
        
        #floatExLeftTwo {
            background-color:#939;	
        }
        

(X)HTML Code:

        <div id="floatExCont">
        	&div id="floatExLeftOne">Div One</div>
        	<div id="floatExLeftTwo">Div Two</div>
        </div>
        

Result:

Div One
Div Two

Two divs floated side by side to the left

Floating items right

CSS Code:

        #floatExCont {
            float:left;
            overflow:auto;
            background-color:#09C;
            border:1px solid #039;
        }
                    
        #floatExRightOne, #floatExRightTwo {
            float:right;
            width:60px;
            height:60px;                
        }
        
           #floatExRightOne {
            background-color:#939;
        }
        
        #floatExRightTwo {
            background-color:#FC3;	
        }
        

(X)HTML Code:

        <div id="floatExCont">
        	&div id="floatExOne">Div One</div>
        	<div id="floatExTwo">Div Two</div>
        </div>
        

Result:

Div One
Div Two

Two divs floated side by side to the right

Note — as you can see from above, the first div is on the right and the second div is on the left. Whichever element you want to come first, must be last in your HTML.

Dimensions...(a side-note)

Just to let you know, not giving a block element a width or height is the equivalent of setting its width and height to auto: width:auto and height:auto. Empty elements (elements without any content) require a width and height in lenghth units that is not auto, otherwise they will not render on screen.

It is also a good idea to specify a width and height on your images, otherwise, if they render after the content, there might not be sufficient space for them, and your page could end up looking a bit strange (I don't always do this, but it is advisable!) This happens because the document doesn't know how big the images are, so it can't create the desired space, so you end up with the text overlapping your images.

So just remember to specify dimensions where needed. It will save you a lot of hassle!

Issues can arise with floats leaking out and affecting other elements on your page. For more, check out How to eliminate unnecessary tags by using CSS clear property and How to combat float leakage.

Clear a float

To clear a float we use the clear property, which has four values: right, left, both and none.

Clear left floats

To clear items floating to the left of an element, we use clear:left. Please ensure that the floats you intend to clear are floated to the left. clear:left will not work on right floated elements and vice-versa.

CSS Code:

        #clearExCont {
            overflow:auto;                
        }
        
        .clearLeftExOne, .clearLeftExTwo, .clearLeftExThree, .clearLeftExFour, .clearLeftExFive  {
            float:left;
        }
                      
        .clearLeftExOne {
            background-color:#33F;	
        }
        
        .clearLeftExTwo {
            background-color:#903;	
        }
        
        .clearLeftExThree {
            background-color:#6C6;	
            clear:left;            
        }
        
        .clearLeftExFour {
            background-color:#C9F;	            
        }
        
        .clearLeftExFive {
            background-color:#C06;	                        
        }      
        

(X)HTML Code:

        	<div id="clearExCont">
            	<div class="clearLeftExOne">Div One</div>
                <div class="clearLeftExTwo">Div Two</div>
                <div class="clearLeftExThree>Div Three</div>
                <div class="clearLeftExFour">Div Four</div>
                <div class="clearLeftExFive">Div Five</div>
            </div>
        

Result:

Div One
Div Two
Div Three
Div Four
Div Five

The third div is dropped to a new line and the floats to the left of it have been cleared.

Clear right floats

To clear items floating to the right of an element, we use clear:right. Please ensure that the floats you intend to clear are floated to the right. clear:right will not work on left floated elements and vice-versa.

CSS Code:

        #clearExCont {
            overflow:auto;                
        }
        
        .clearRightExOne, .clearRightExTwo, .clearRightExThree, .clearRightExFour, .clearRightExFive {
            float:right;
        }
        
        .clearRightExOne {
            background-color:#33F;	
        }
        
        .clearRightExTwo {
            background-color:#903;	
        }
        
        .clearRightExThree {
            background-color:#6C6;	                
            clear:right;
        }
        
        .clearRightExFour {
            background-color:#C9F;	
        }
        
        .clearRightExFive {
            background-color:#C06;	
        }
		

(X)HTML Code:

        	<div id="clearExCont">
            	<div class="clearRightExOne">Div One</div>
                <div class="clearRightExTwo">Div Two</div>
                <div class="clearRightExThree">Div Three</div>
                <div class="clearRightExFour">Div Four</div>
                <div class="clearRightExFive">Div Five</div>
            </div>
        

Result:

Div One
Div Two
Div Three
Div Four
Div Five

All floats to the right of the third div have been cleared.

Clear all floats regardless of which side they are on

To clear all floats, regardless of what float is applied to an element, or what floats surround it, set the float on the element in question to none and add clear:left.

CSS Code:

        #clearExCont {
            overflow:auto;                
        }
        
        .clearNoneExOne, .clearNoneExTwo, .clearNoneExThree,  .clearNoneExFour, .clearNoneExFive {
            width:60px;
            height:60px;
        }
        
        .clearNoneExOne, .clearNoneExTwo {
            float:left;
        }
        
         .clearNoneExFour, .clearNoneExFive {
            float:right;
        }
        
        .clearNoneExOne {
            background-color:#33F;	
        }
        
        .clearNoneExTwo {
            background-color:#903;	
        }
        
        .clearNoneExThree {
            background-color:#6C6;	  
            float:none;
            clear:both;                             
        }
        
        .clearNoneExFour {
            background-color:#C9F;	
        }
        
        .clearNoneExFive {
            background-color:#C06;	
        }
		

(X)HTML Code:

        	<div id="clearExCont">
            	<div class="clearNoneExOne">Div One</div>
                <div class="clearNoneExTwo">Div Two</div>
                <div class="clearNoneExThree">Div Three</div>
                <div class="clearNoneExFour">Div Four</div>
                <div class="clearNoneExFive">Div Five</div>
            </div>
        

Result:

Div One
Div Two
Div Three
Div Four
Div Five

The third div is dropped to a new line and there are no floats on either side of it.

For more on the CSS clear property, check out my tutorial on How to eliminate unnecessary tags by using CSS clear property.

Wrap text round an image

We use the float property (you must be getting sick of it by now!) to wrap text round an image. Firstly, position the image at the beginning of the element whose text you plan to wrap – even if you want the image appear to the right of the text. Then give the image a float of either right or left – right if you want the image to go to the left of the text, left if you want it to go to the right of the text.

Image on the left

Here's what to do if you want your image to be on the left and your text to flow round it on the right.

CSS Code:

        img {
        	float:left;
        	margin:0 10px 0 0; /* Let's put some space between the image and our text */
        }           
        

(X)HTML Code:

            <img src="images="myimage.jpg" alt="Whatever" />
            <p>Some text....</p>
        

Result:

A nice Ali Larter picture

Morbi a orci massa, vel porttitor enim. Suspendisse eu nisi nulla. Pellentesque vitae lorem lorem. Donec tristique nibh in libero tempus ornare vel nec nisl. Maecenas facilisis scelerisque faucibus. Ut id augue risus, sit amet commodo nibh. Fusce congue nisi id augue iaculis aliquam. Phasellus lobortis lobortis erat, eget dictum ante fringilla at. Aliquam varius ante vel sapien tempor ac sollicitudin ligula congue. Maecenas a augue dui. Nam pretium odio eget tellus egestas vitae sodales tortor suscipit. Nullam aliquam dolor vel libero suscipit vel feugiat nibh vehicula. Donec eu ipsum lorem. Donec id erat est, quis ultricies sem. Curabitur ac sem velit, ac fermentum risus. Duis suscipit facilisis facilisis.

Note — remember to clear the float after the text, either by placing the image and text in a container (like I've done, if you view the source), or by placing clear:left on the element after.

If you use the container method and your container doesn't have any dimensions, you may notice that the float is leaking out. This is because your container needs to be told it has contents. To overcome this, either give your container fixed dimensions or apply the following CSS to it:

        	#container {            	
                height:100%; /* Only apply height:100% if you're bothered about IE6. */
                overflow:auto;
            }
        

This will tell our container to expand to fit its contents.

The height:100% is only needed for IE6. overflow:auto is sufficient for all other modern browsers.

For more on how to get a container to expand to fit its contents, see The CSS overflow property and why it's so useful and The top 10 things you've always wanted to do in CSS >> Make a div expand to fill its content.

Image on the right

Here's what to do if you want your image to be on the right and your text to flow round it on the left.

CSS Code:

        	img {
            	float:right;
                margin:0 0 0 10px; /* Let's put some space between the image and our text */
            }           
        

(X)HTML Code:

        	<img src="images="myimage.jpg" alt="Whatever" />
            <p>Some text....</p>
        

Result:

Ali Larter...need I say more...oh, yeah, how to wrap text round an image on the left!

Morbi a orci massa, vel porttitor enim. Suspendisse eu nisi nulla. Pellentesque vitae lorem lorem. Donec tristique nibh in libero tempus ornare vel nec nisl. Maecenas facilisis scelerisque faucibus. Ut id augue risus, sit amet commodo nibh. Fusce congue nisi id augue iaculis aliquam. Phasellus lobortis lobortis erat, eget dictum ante fringilla at. Aliquam varius ante vel sapien tempor ac sollicitudin ligula congue. Maecenas a augue dui. Nam pretium odio eget tellus egestas vitae sodales tortor suscipit. Nullam aliquam dolor vel libero suscipit vel feugiat nibh vehicula. Donec eu ipsum lorem. Donec id erat est, quis ultricies sem. Curabitur ac sem velit, ac fermentum risus. Duis suscipit facilisis facilisis.

Note — remember to clear the float after the text, either by placing the image and text in a container (like I've done, if you view the source), or by placing clear:left on the element after.

If you use the container method and your container doesn't have any dimensions, you may notice that the float is leaking out. This is because your container needs to be told it has contents. To overcome, either give your container fixed dimensions or apply the following CSS to it:

        	#container {            	
                height:100%; /* Only apply height:100% if you're bothered about IE6. Without it, the float will leak out in IE6 */
                overflow:auto;
            }
        

This will tell our container to expand to fit its contents.

The height:100% is only needed for IE6. overflow:auto is sufficient for all other modern browsers.

For more on how to get a container to expand to fit its contents, see The CSS overflow property and why it's so useful and The top 10 things you've always wanted to do in CSS >> Make a div expand to fill its content.

Make a div expand to fill its content

If you want a div (or any container, for that matter) to expand to fit its content, you need to give it an overflow:auto. overflow tells the browser what to do with the content that spills over an element's boundaries. Setting overflow:auto tells the browser you want the overflow to be automatic, which means the element stretches to accommodate its contents.

Example

CSS Code:

        #myDiv {
        	background-color:orange;
        	overflow:auto;
        }
		

Result:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce in diam ante, sit amet molestie risus. Etiam pellentesque aliquet enim, ut molestie enim suscipit vel. Donec odio est, cursus ac pulvinar a, elementum non elit. Donec non eros in neque dictum interdum ut hendrerit turpis. Morbi posuere massa at sapien elementum aliquet. Duis vel venenatis neque. Praesent venenatis tortor eget felis venenatis a pulvinar tortor laoreet. Vestibulum a nunc at metus ullamcorper rhoncus. Aenean malesuada pharetra justo in sollicitudin.

The div has stretched to fill its contents.

IE6

In order for this to work in IE6 (if you care about IE6, that is), you will need to apply height:100% to your container.

For more on overflow:auto and making an element expand to fit what is inside it, check out The CSS overflow property and why it's so useful

There are four states of the anchor (link) tag:

It's quite common to write your links like this:

        a {
        	color:red;
        	font-weight:bold;
        }
        a:hover {		
        	color:blue;
        	text-decoration:none;
        }	
		

This method involves manipulating the a tag directly and its hover state, a:hover. However, I prefer to add styles to the a:visited as well as a and a:hover, as I feel the visited state is useful, as it tells you what pages you have already visited.

To add pizzazz to your links try manipulating the various link states. Experimentation is your best friend :).

For more on CSS and links, see CSS 101 | Part Nine - CSS and Links.

Have your block element stretch to fit the visible screen

This technique basically makes your block element fill the whole of the screen. This is useful, for instance, when you have a background image in a div, that you want to fill the screen at all times. To achieve this, you need to tell your element exactly what space to fill and this is where the body and html tags come in.

			body, html {
				width:100%;
				height:100%;
			}
		

We give the body and html a width and height of 100%, which causes our block element to stretch to fill the screen. If you want your element to fill the whole screen, you must specify a width and height of 100%. If you only want it to fill the screen vertically and you're not so bothered about the width, then it's only necessary to enter a height. If you want to achieve the "ultimate" full screen effect, it is often desirable to set the body's margins to 0, which will eliminate any white space round your content, thus pushing it right up against the bounds of the window.

Remove page margins, so your content pushes up against the sides, top and bottom of the screen

Have you ever wondered what causes that 8px or so gap round the sides of the screen when your website is supposed to fit the screen perfectly, or perhaps when you open an image directly in a new window?

Page with default margins

Well, it's the body’s margins. We remove them by saying:

			body {
				margin:0;				
			}
		

And voila, we're done! No ugly white space.

Page with no margins

For more on what you can do with margins and padding in CSS, see The CSS way to style margins and padding.

Create a horizontal menu

A horizontal menu from www.sunandsnow.co.uk

Horizontal menus are everywhere, and they're very useful. Creating one isn't as daunting a task as you might think - and, no, it doesn't involve a single hack. It's pure CSS. Just the way we like it!

When we create an HTML menu, we are (hopefully) using the ul or ol elements. CSS list items (lis) naturally appear one under the other. But we don't want this. So to get round it, we change the li to display:inline.

			li {
				display:inline;				
			}
		

Perhaps you want to remove the bullet-points and control those margins.

			ul {
				list-style-type:none;
				margin:0;
				padding:0
			}
			li {
				display:inline;				
			}
		

And maybe you want to align the list elements to the centre.

			li {
				display:inline;
				text-align:center;
			}			
		

Converting a block element to an inline element and vice-versa

Block and inline elements are the two main types of elements in CSS. Sometimes it's handy to switch between the two. A good example is when you want your links to become buttons. To do this, we manipulate the CSS display property.

The display property has many values, though not all of them are widely supported. Here I am going to list the values that are supported by all modern browsers.

  • none - will not render the element at all (this it different from visibility:hidden as it completely removes an element from the page, and not just from view)
  • block - will render a block element
  • inline - will render an inline element

Converting an inline element to a block element

To convert an inline element to a block element, we do the following:

			a.button {
				display:block;				
			}			
		

Converting a block element to an inline element

And back again...

			li.button {
				display:inline;				
			}			
		

Converting elements to block elements is particularly useful when creating horizontal menus that have list items of definite widths. For more on this topic, see Horizontal menus and list items with definite widths. If you are interested in horizontal menus with automatic widths, why not visit Horizontal menus and list items with definite widths?

A block element

Block elements will not fit their content, horizontally. Unless a width is specified that is not auto or 100%, they will expand horizontally to fit their parent container. Vertically they will fit their content, unless otherwise specified. Both padding and margins can be applied to them.

An inline element

Inline elements "shrink-wrap" to fit their content both horizontally and vertically, and only left and right padding and margins will have an effect.

Got any questions or comments? Feel free to mail me @ helen@alternategateways.com.

Share this:

Back to resources.