Free Web Development Online Tutorials, Learn to Code
CSS width height in percentage, css background width height, css image width height cover

CSS Width Height Example

In this tutorial you will learn how to set css width and height of any element like div, p or any other html element, in my example i will show how to work with div tag height and width, because most of the time you will be dealing width "div" while designing a responsive web page.

CSS height width dynamic

Depending on your layout design requirement you may set width and height either fixed or in percentage.

Here is an example of how you can set fixed width and height of html div, span ect

width:400px;
height:200px;

CSS Height and Width in Percentage

However, in most of the cases, when you want your page element to be responsive for different device and browser, you need set css width in percentage.

width:50%;

Suppose you have two div(s) in your web page, you can define them like example below.

    .divLeft {
        width:30%; 
        float:left;       
    }

    .divRight {
        width: 70%;
        float: right;
    }

But remember, when you are considering the entire width in percentage then there should not be any margin in that div.

Means, in above example, I have mentioned width 30% and 70%, that means the total 100% width is consumed, now if i define margin in my div, that will be wrong, even one pixel margin will go out of 100% container width, as a result the div on right side will come at below instead of appearing at right side.

CSS height in percentage

Set css body width height

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

Now we see how to set height in percentage, normally you do not need to set the height of any div, because it automatically adjusts the height depending on content inside it.

However, you need to know how it works! If you set the height on any div in percentage, it may not work until you set the height of body and html in percentage.

Here is an example of how you can set the height in percentage works perfectly.

html,body { height: 100%; margin: 0; }
.div1 { background: red; height: 20%; }
.div2 { background: blue; height: 30%; }
.div3 { background: green; height: 50%; }

CSS background width height

Now we see how to set background width and height using CSS; background width and height can be set by using background-size property, it takes two values.

background-size: 100% 100%;
//OR
background-size: 800px 200px;

first value: width of the image, second value: height

You may be interested to know how to work with CSS Background

CSS Style Examples