Skip to main content

Width and Height in the CSS Box Model (Live Playground)

Width and height properties are crucial components of the CSS box model, determining the size of the content area of an element. In this tutorial, you will learn about the width and height properties, how to set them, and how they affect the layout of elements, along with sample code and simple explanations.

Setting width and height

You can set the width and height of an element using the following properties:

  • width
  • height

Example:

CSS
div {
background-color: lightblue;
width: 300px;
height: 200px;
}
HTML
<div>This div element has a fixed width and height.</div>

In this example, the div element has a fixed width of 300px and a fixed height of 200px.

Live Playground, Try it Yourself

Using percentages for responsive design

You can use percentage values to make your elements responsive to the size of their container:

Example:

CSS
.container {
width: 80%;
margin: 0 auto;
}

div {
background-color: lightblue;
width: 50%;
height: 50%;
}
HTML
<div class="container">
<div>This div element has a responsive width and height.</div>
</div>

In this example, the div element has a responsive width and height that adjust based on the size of its container.

Live Playground, Try it Yourself

The effect of width and height on layout

The width and height properties affect the content area of an element and can influence the positioning of surrounding elements. They do not, however, affect the padding, border, or margin.

Example:

CSS
.container {
display: flex;
}

.box {
background-color: lightblue;
margin-right: 10px;
width: 100px;
height: 100px;
}

.box-large {
width: 200px;
height: 200px;
}
HTML
<div class="container">
<div class="box">Small box</div>
<div class="box box-large">Large box</div>
</div>

In this example, the larger box has a bigger content area but retains the same padding, border, and margin as the smaller box.

Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned about the width and height properties in the CSS box model and how to set them. By understanding the role of width and height in the box model and how they affect the layout of elements, you can create more visually appealing and consistent designs across your web pages.