CSS Height and Width - Detailed Overview

Introduction to CSS Height and Width

The height and width properties in CSS control the size of an element. They can be set using various units and can be applied to block-level and inline-level elements.

Setting Width

The width property specifies the width of an element. For example:

div {
    width: 200px;
    border: 1px solid #ddd;
}
Width: 200px

Setting Height

The height property specifies the height of an element. For example:

div {
    height: 150px;
    border: 1px solid #ddd;
}
Height: 150px

Auto Width and Height

The width and height properties can be set to auto, which allows the element to adjust based on its content or the container. For example:

div {
    width: auto;
    height: auto;
    border: 1px solid #ddd;
}
Width and height: auto

Percentage Width and Height

Width and height can be set using percentage values, which are relative to the parent element's dimensions. For example:

div {
    width: 50%;
    height: 50%;
    border: 1px solid #ddd;
}
Width: 50%, Height: 50%

Viewport Units

Viewport units allow you to set the height and width relative to the viewport size. For example:

div {
    width: 50vw;
    height: 50vh;
    border: 1px solid #ddd;
}
Width: 50vw, Height: 50vh

Min and Max Width/Height

The min-width, max-width, min-height, and max-height properties control the minimum and maximum size of an element. For example:

div {
    min-width: 100px;
    max-width: 300px;
    min-height: 100px;
    max-height: 300px;
    border: 1px solid #ddd;
}
Min and Max dimensions