Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use percentage value for div's width in CSS?

Tags:

css

I am reading articles about css. I found out that many of writers suggest to use % value for div's width or height.

I am using pixels all the time.

Why should I use % value for div's width or height instead of pixels?

What are the advantages?

like image 255
Moon Avatar asked Feb 13 '11 06:02

Moon


2 Answers

I, personally, dislike websites which have a % width for the main content area because of the inconsistency. It's best to use a pixel width of about 1000 pixels, maybe a bit less, for the whole website so that it will work for all resolutions.

As for elements inside the main content area, I tend to use percent widths because I don't really want to both with calculating the exact pixel values. The result is set in stone anyway because the thing that it's a percentage of is constant, as opposed to the monitor's resolution, which varies between users.

To sum it up: only use percentages when every user is going to get the same result because of a parent element having a fixed (pixel) width. Otherwise there will be inconsistencies in your design, making it so that you can't use any flashy images and the website may look ugly to users with giant / tiny monitors. If you are going to use percentage widths you simply have to test the website with different resolutions!

like image 122
Matt Eskridge Avatar answered Sep 18 '22 02:09

Matt Eskridge


Save the following html to a file and open it with your web browser. Now change the size of the web browser window, notice the percent will expand and contract and the pixels don't.

<!DOCTYPE html>
<html>
<head>
<title>Pixels and Percents</title>
<style>
html,body {
    margin:0;
    width:100%;
    height:100%;
    background:blue;
}

.pixels {
width:100px;
height:20px;
background:green;
}

.percent {
width:50%;
height:50%;
background:red;
}

</style>
<head>
<body>
<div class="pixels">
PIXELS
</div>
<div class="percent">
PERCENT
</div>
</body>
</html>
like image 42
Tobias Avatar answered Sep 19 '22 02:09

Tobias