Skip to main content
Practice

Width and Height

The width and height properties in CSS define the width and height of HTML elements.

max-width and max-height restrict the maximum width and height of HTML elements, while min-width and min-height set minimum width and height boundaries.

Units for defining width and height include pixels (px), percentages (%), and more.

A "pixel" is the smallest unit that can be displayed on a screen, specifying a fixed size regardless of device or resolution, while a "percentage" specifies a size relative to the parent element in which the element is contained.

For more details on units, please refer to Chapter 2.


width and height

The width and height properties specify the horizontal width and the vertical height of an element, respectively.

Example code:

CSS
.structure {
width: 300px; /* The width of the structure is 300 pixels */
height: 150px; /* The height of the structure is 150 pixels */
}

CSS: Restricting HTML Element Size

Adjusting the size of elements in web design is important for improving user experience and implementing responsive design.

You can limit the size of elements using the max-width, max-height, min-width, and min-height properties.


max-width

  • The max-width property specifies the maximum width of an element.

  • It restricts the element's width from exceeding the specified value.

CSS
.box {
max-width: 300px;
width: 100%;
}

In the example above, the box's width will expand according to its parent element's width but will not exceed 300px.


max-height

  • The max-height property specifies the maximum height of an element.
  • It restricts the element's height from exceeding the specified value.
CSS
.box {
max-height: 150px;
height: auto;
}

min-width

  • The min-width property specifies the minimum width of an element.
  • It ensures that the element's width does not go below the specified value.
CSS
.box {
min-width: 200px;
width: 100%;
}

In the example above, the box's width will shrink according to its parent element's width but will not go below 200px.


min-height

  • The min-height property specifies the minimum height of an element.
  • It ensures that the element's height does not go below the specified value.
CSS
.box {
min-height: 100px;
height: auto;
}

Follow the highlighted parts of the code and try typing them out yourself.

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.