CSS height

The CSS height property is used to define the height of an element. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 1px solid red; height: 320px;}
   </style>
</head>
<body>
   
   <div>
      <h2>The height Property</h2>
      <p>This is an example of height property.</p>
   </div>
   
</body>
</html>
Output

The height Property

This is an example of height property.

Note - The two properties that can override the height property are, min-height and max-height.

CSS height Syntax

The syntax of height property in CSS, is:

height: x;

The value of x should be any of the following:

CSS height Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 1px solid red; margin: 10px 0; padding: 8px;}
      div.b{height: auto;}
      div.c{height: 120px;}
      div.d{height: 50vh;}
   </style>
</head>
<body>
   
   <div class="a">Without height Property</div>
   <div class="b">height: auto</div>
   <div class="c">height: 120px</div>
   <div class="d">height: 50vh</div>
   
</body>
</html>
Output
Without height Property
height: auto
height: 120px
height: 50vh

Note - The vh in 50vh refers to vertical height of current screen. The 100vh is used to apply the same height as of current screen height.

Note - In case, if the specified height of an element does not fit the content in it, then the content goes overflowed. For example:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 3px solid red; height: 60px;}
   </style>
</head>
<body>
   
   <div>
      <p>This is para one</p>
      <p>This is second para</p>
      <p>This is another para</p>
   </div>
   
</body>
</html>
Output

This is para one

This is second para

This is another para

However we can handle the overflowed content using the overflow property. For example, add the following CSS code in above example:

overflow: auto;

Now the output will be:

This is para one

This is second para

This is another para

The height of the DIV is still same, but the content does not gets overflowed, rather it gets wrapped using a slider. Therefore, you can scroll to see the remaining content of the DIV.

Let me create one more example to complete the tutorial on height property in CSS:

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 2px solid red; padding: 8px;}
      div.outer{height: 320px;}
      div.inner{height: 50%;}
   </style>
</head>
<body>
   
   <div class="outer">
      <div class="inner">CODESCRACKER</div>
   </div>
   
</body>
</html>
Output
CODESCRACKER

In above example, the height of inner DIV is the half or 50% the height of outer DIV, because inner DIV's height is set to 50%.

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!