The height property specifies the vertical dimension of an element’s content area. By default, most elements have a height of auto, meaning they grow or shrink based on the content inside them.
Defining Height Values
You can control the height of an element using several different units of measurement:
auto: The default value. The browser calculates the height based on the content.- Length (
px,cm,rem): Sets a fixed height. - Percentage (
%): Sets the height relative to the height of the parent container. Note: For percentage height to work, the parent must have a defined height. - Viewport Height (
vh): Sets the height relative to the browser window ($1\text{vh} = 1\text{%}$ of the viewport height).
Note that while defining a fixed height for an element, if the content of the element is larger than the size of the element, overflow will occur.
Example Code:
.outer-div{
height: 200px; /* Always 200 pixels high */
background-color: #CCC;
padding: 40px 20px;
}
.inner-div-1 {
height: 80px; /* Always 80 pixels high */
background-color: #0e8bff;
margin:20px;
text-align: center;
border: 1px solid red;
}
.inner-div-2 {
height: 40px; /* Always 40 pixels high */
background-color: #0e8bff;
margin:20px;
text-align: center;
border: 1px solid red;
}
.full-screen-section {
height: 100vh; /* Takes up the entire screen height */
}
Output
Controlling Limits (Min & Max Height)
Sometimes you don’t want a fixed height, but you want to ensure the element doesn’t get too small or too large.
min-height: Ensures an element is at least a certain height. If the content grows, the element grows with it.max-height: Prevents an element from growing beyond a certain point. If content exceeds this, it will overflow.
Example Code:
.ht{
min-height: 50px; /* Won't shrink smaller than this */
max-height: 100px; /* Won't grow larger than this */
background-color: white;
}
Output
a min height of 50px even if
the content height is smaller than
50px. And it will extend up to 100px
depending on the size of the content.
Even if the content height is more than 100px
the height will remain at 100px and overflow will occur if content is more than px.
This element will take up a min height of 50px even ef the content height is smaller than 50px. And it will extend up to 100px depending on the size of the content. Even if the content height is more than 100px the height will remain at 100px and overflow will occur if content is more than px.
Important Note on Block vs. Inline
The height property cannot be applied to inline elements (like <span> or <a>). To give an inline element height, you must first change its display property to display: block; or display: inline-block;.