The CSS height and width properties are used to effectively set the dimensions of an element.
CSS Height and Width
Playground Example: To make things simpler, you can click the button below to open the playground, which comes with pre-filled HTML and CSS.
In the editor, you will see HTML, CSS, and JS input on the left/top, and the output on the right/bottom.
Below is the syntax for adding height and width:
Selector {
height: value;
width: value;
}
- The selector can be any one or more of those discussed previously in CSS Selectors.
- " height" and "width" are the property key
- "value" can be in pixels, percentage, auto or inherit.
Example:
/* setting height and width */
.element2 {
height: 70px;
width: 50%;
}
Try changing the value in the playground and observe how the area of the element changes.
It is important to bear in mind that "height" and "width" are designed to determine the dimensions of the content box within an element. Notably, these properties specifically exclude any considerations for padding, borders, or margins.
Thus, their primary function is to define the precise height and width of the content area within the element itself, excluding any additional spacing such as padding, borders, and margins that may surround it.
Want to practice more? Click here for more hands-on exercise.
References: