Skip to main content

CSS Height And Width

The CSS height and width properties are used to define the height and width of an element.

Here are some things to keep in mind when using these properties:

  • By default, the height and width properties are set to auto, which means that the element will be sized based on its content.
  • You can set the height and width properties to specific pixel values, such as height: 100px; and width: 200px;.
  • You can also use relative units, such as percentages, to define the height and width of an element. For example, height: 50%; would set the height of the element to be 50% of its containing block's height.
  • If you specify a value for only one of the height or width properties, the other property will adjust automatically to maintain the element's aspect ratio. For example, if you set width: 200px; but don't specify a value for height, the height of the element will adjust automatically to maintain the aspect ratio.

CSS Height and Width Example

An example of how to use CSS height and width properties:

Editor

Loading...

CSS height and width Values

The height and width properties can accept a variety of values to specify the size of an element.

Here are some of the most common values you can use:

Fixed Values

Fixed values are specific pixel or unit values that set a fixed size for an element.

As an example:

height: 200px;
width: 300px;

Percentage Values

Percentage values set the size of an element based on a percentage of its parent container.

As an example:

height: 50%;
width: 75%;

Auto Value

The auto value sets the height or width of an element to be determined automatically based on its content or other factors.

As an example:

height: auto;
width: auto;

Max and Min Values

The max-height, max-width, min-height, and min-width properties allow you to set limits on the maximum and minimum size of an element.

As an example:

max-height: 500px;
min-width: 100px;

Viewport Units

Viewport units allow you to set the size of an element relative to the size of the browser window. The most commonly used viewport units are vh and vw, which represent 1% of the viewport height and width, respectively.

As an example:

height: 50vh;
width: 75vw;

Content-Based Values

The fit-content value sets the size of an element based on its content, while also accounting for any specified minimum and maximum sizes.

As an example:

height: fit-content;
width: fit-content;
min-height: 100px;
max-width: 500px;

Flexbox Values

If you're using flexbox layout in CSS, you can use the flex-basis property to set the initial size of a flex item.

As an example:

flex-basis: 200px;

Grid Values

If you're using CSS grid layout, you can use the grid-template-rows and grid-template-columns properties to define the rows and columns of your grid, and set their size using the same values as the height and width properties.

As an example:

grid-template-rows: 100px 200px 50px;
grid-template-columns: 1fr 2fr 1fr;