CSS Height and Width

CSS height and width properties are used to control the size of elements. These properties can be applied to block-level and inline-level elements to define their dimensions.

Height and Width Properties

The `height` and `width` properties specify the dimensions of an element. You can use absolute values, percentages, or viewport units.

Height Property

The `height` property sets the height of an element. It can be specified in various units, such as pixels, percentages, or viewport units.


/* Height examples */
.full-height {
    height: 100vh; /* Full viewport height */
}

.container {
    height: 400px; /* Fixed height in pixels */
}

.responsive-height {
    height: 50%; /* 50% of the parent element's height */
}

        

Width Property

The `width` property sets the width of an element. Similar to height, it can be specified using pixels, percentages, or viewport units.


/* Width examples */
.full-width {
    width: 100vw; /* Full viewport width */
}

.box {
    width: 300px; /* Fixed width in pixels */
}

.responsive-width {
    width: 80%; /* 80% of the parent element's width */
}

        

Aspect Ratio

To maintain a consistent aspect ratio, you can use the `aspect-ratio` property. This helps ensure that an element maintains a specific ratio between width and height.


/* Aspect Ratio example */
.aspect-ratio {
    aspect-ratio: 16 / 9; /* Aspect ratio of 16:9 */
    width: 100%;
    height: auto;
}