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 limit the maximum width and height of HTML elements, while min-width and min-height set the minimum width and height of HTML elements.

Units for setting width and height include pixels (px) and percentages (%), among others.

Pixels represent a fixed size irrespective of the device and resolution, while percentages define the size relative to the element's parent container.

Detailed information about units is covered in Chapter 2.


width and height

The width and height properties specify the horizontal width and 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: Limiting size of HTML elements

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

You can restrict 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 prevents the element's width from exceeding the specified value.
CSS
.box {
max-width: 300px;
width: 100%;
}

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


max-height

  • The max-height property specifies the maximum height of an element.
  • It prevents 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 the element's width does not fall below the specified value.
CSS
.box {
min-width: 200px;
width: 100%;
}

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


min-height

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

Follow the highlighted parts of the code and try inputting it yourself.

Want to learn more?

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