Defining Width and Height Utilities

Tutorial 3 of 5

Introduction

This tutorial aims to teach you how to define width and height utilities in CSS. CSS, short for Cascading Style Sheets, is used to style and layout web pages, and is an essential part of web development. By the end of this tutorial, you'll be able to control the dimensions of your HTML elements, giving you more power over your web page design.

You will learn:
- How to define width and height properties in CSS.
- How to apply these properties to HTML elements.

Prerequisites:
- Basic knowledge of HTML and CSS.

Step-by-Step Guide

In CSS, we can control the dimensions of an element using the 'width' and 'height' properties. These properties can be set using different units like pixels (px), percentage (%), viewport height (vh), viewport width (vw), etc.

Width property: The 'width' property in CSS defines the horizontal dimensions of an element.

Height property: The 'height' property in CSS defines the vertical dimensions of an element.

Code Examples

Example 1: Setting width and height in pixels

div {
   width: 200px;  /* set the width of the div to 200 pixels */
   height: 150px; /* set the height of the div to 150 pixels */
}

In this example, we've used pixels (px) to set the dimensions. When the webpage is rendered, the div will have a width of 200 pixels and a height of 150 pixels.

Example 2: Setting width and height as a percentage

div {
   width: 50%;  /* set the width of the div to 50% of the parent element */
   height: 50%; /* set the height of the div to 50% of the parent element */
}

In this example, the dimensions are set as a percentage of the size of the parent element. This is useful when you want your website to be responsive and adapt to different screen sizes.

Summary

In this tutorial, we've learned about the CSS 'width' and 'height' properties and how to apply them to HTML elements. We've also looked at different units that can be used to set these properties.

Next Steps:
Continue exploring CSS properties such as 'min-width', 'max-width', 'min-height', and 'max-height' for more control over your element sizing.

Additional Resources:
- MDN Web Docs: CSS
- W3Schools: CSS

Practice Exercises

Exercise 1: Create an HTML page with a div element. Set the width and height of the div to 300px.

Exercise 2: Modify the div element from the first exercise to have a width and height of 50% of the body element.

Exercise 3: Create an HTML page with a div element. Set the width to 100vw (viewport width) and the height to 50vh (viewport height).

Solutions and Tips:
Experiment with different values and units for the width and height properties. Try resizing your browser window to see how the div element changes. The goal is to get a feel for how these properties work in different contexts. Happy coding!