best websites of the world

FRONT END DEVELOPER/
WEB DEVELOPER/
WEB DESIGNER/
LONDON/ SURREY/

CSS em Units Explained

Most web designers and web developers have relied for years on pixel values. I for one didn’t really know allot about using em values. This article will hopefully try to explain what em units are and how you could use them in your projects.

What exactly is an em value?

Formal definition from of the unit

“Equal to the computed value of the ‘font-size’ property of the element on which it is used.”

So if we have set the font size of an h1 element to 20px and then we used the following code:

H1{
	font-size: 20px;
	line-height: 1.2em;
}

this would set the line height to 20% bigger than the font size set. So it would be 24px high.

But what if you don’t set the size of your font? Generally in your CSS tree you will have set font size’s at some point, I don’t really see how you cant! But if no font size has been set the size on an em unit will result to 16px.

The only way you can learn is by doing! So lets try one more.

Say we have a div with a font size set to 20px how would you go about setting the width and the height of the div to be the same as 100px? Well 100 / 20 = 5 so you would set the height and the width of the div to be 5em like so:

.div {  
    font-size: 20px;  
    width: 5em;  
    height: 5em;  
}

A little tip – comments

Recently I have completed some work in collaboration with some other web designers and developers. To be polite the codes comments were particularly light. Its not really that necessary to comment CSS code quite as much as if you were writing in PHP or C# however in the case of using em it is really helpful. For the example above I like to comment like the example below. This really helps after a while to get your head round em units and you will be grateful when you go back to look at your CSS file in a few months time!

.div {  
    font-size: 20px;  
    width: 5em; /* 100px / 20px = 5em */
    height: 5em; /* 100px / 20px = 5em */
}

Round up

I found it quite hard to get into the habit of using em units after using pixels for such a long time. However the new releases of the popular css frameworks, Foundation.Zurb and Bootstrap include the use of em units.

While current trends in web design make use of responsive layouts I believe the use of pixels and percentages are necessary for setting container sizes etc. However the use of em units become useful when setting sizes in relation to fonts.

Search

Social

Post a Comment

Your email is kept private. Required fields are marked *