Menu
Coddy logo textTech

Width and Height

Part of the Styling with CSS section of Coddy's HTML journey — lesson 37 of 76.

In CSS, the width and height properties are used to set the dimensions of an element's content area. These properties are essential for controlling the size and layout of elements on your web pages. 

Here's the basic syntax for using the width and height properties:

selector {
    width: value;
    height: value;
}
  • width: The width of the element's content area.
  • height: The height of the element's content area.
  • value: The desired width or height value, which can be specified in pixels (px), ems (em), percentages (%), or other valid CSS units. You can also use the keyword auto to let the browser automatically calculate the width or height based on the content.

For example:

div {
    width: 300px;
    height: 200px;
}

img {
    width: 100%;
    height: auto;
}

In this example, all <div> elements have a width of 300px and a height of 200px, while all <img> elements have a width that takes up 100% of their parent element's width and a height that is automatically calculated to maintain the aspect ratio.

challenge icon

Challenge

Easy

You are given an HTML document with a division (<div>) and an image (<img>). Your task is to use the width and height properties to set the dimensions of these elements. Follow the steps below:

  1. Write a CSS rule that targets the <div> element. Set the width to 400px and the height to 250px.
  2. Write a CSS rule that targets the <img> element. Set the width to 300px and the height to auto.

Cheat sheet

The width and height properties control the dimensions of an element's content area:

selector {
    width: value;
    height: value;
}

Values can be specified in pixels (px), ems (em), percentages (%), or use auto for automatic calculation:

div {
    width: 300px;
    height: 200px;
}

img {
    width: 100%;
    height: auto;
}

Try it yourself

<html>
<head>
    <title>Width and Height</title>
    <style>
        /* Write CSS rules here */
    </style>
</head>
<body>
    <div style="border:2px solid black;">This is a division.</div>
    <img src="https://img.freepik.com/free-photo/abstract-luxury-gradient-blue-background-smooth-dark-blue-with-black-vignette-studio-banner_1258-54865.jpg" alt="Image">
</body>
</html>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Styling with CSS