What are the differences between px,em and % in CSS? Which one should use?

What are the differences between px,em and % in CSS? Which one should use?

Good question,

“px” is for the denotation of pixels and is not as widely used today as it was before responsive layouts.

If has a container for instance:

#container{ height: 100px;
width 100px;
background-color: pink
}

you would get exactly what you asked for.  A pink box would appear on your device (Such as a large screen TV, a computer, a tablet or a cellphone).

That is exactly the problem with pixels. They are a fixed unit of measurement . Now what if your fonts and layout need to be changed according to the media you are using? “ems” would be your redemption. Every font (unless defined otherwise) has a default size. 1em  would be that size. If you want to shrink by a factor of 50% you would use font-size: .5em.

Percentage mostly deals with how much of the screen you want your box to take up. For instance, you want your containing element to be 90% of your screen you would write the following code:

div.background-image{ height: 50%;
width: 50%
}

 

This holds true for any box (and remember. Every object in CSS is a box) within your CSS code.

 

Duda

About the Author

About Thomas

Thomas Duda is a web designer who lives in Bakersfield, CA with his wife and dogs. He is also interested in: Blogging, Writing, Vaping, Fishing, Swimming and Drawing.

Leave a Reply