CSS width

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

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

The width Property

This is an example of width property.

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

CSS width Syntax

The syntax of width property in CSS, is:

width: x;

The value of x should be any of the following:

CSS width Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{background-color: purple; color: white; padding: 8px; margin: 10px 0;}
      div.a{width: auto;}
      div.b{width: 120px;}
      div.c{width: 50%;}
      div.d{width: 12em;}
   </style>
</head>
<body>
   
   <div class="a">width: auto</div>
   <div class="b">width: 120px</div>
   <div class="c">width: 50%</div>
   <div class="d">width: 12em</div>
   
</body>
</html>
Output
width: auto
width: 120px
width: 50%
width: 12em

CSS width: max-content and min-content Example

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{border: 2px solid red; padding: 8px; margin: 10px 0;}
      div.a{width: max-content;}
      div.b{width: min-content;}
   </style>
</head>
<body>
   
   <div class="a">Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, deleniti.</div>
   <div class="b">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolores, nemo.</div>
   
</body>
</html>
Output
Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, deleniti.
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolores, nemo.

CSS Online Test


« Previous Tutorial Next Tutorial »