CSS max-width

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

HTML with CSS Code
<!DOCTYPE html>
<html>
<head>
   <style>
      div{background-color: purple; color: white; margin: 10px 0;}
      div.a{max-width: 120px;}
      div.b{max-width: 220px;}
      div.c{max-width: 220px;}
   </style>
</head>
<body>
   
   <div class="a">Lorem</div>
   <div class="b">Lorem</div>
   <div class="c">Lorem, ipsum dolor sit amet consectetur adipisicing elit.
      Quibusdam minima aperiam reiciendis explicabo ratione quaerat assumenda
      voluptatem magni quasi sint.</div>

</body>
</html>
Output
Lorem
Lorem
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Quibusdam minima aperiam reiciendis explicabo ratione quaerat assumenda voluptatem magni quasi sint.

The initial style rule defines the properties of each div element. It sets the background-color property to "purple" and the color property to "white", giving the div elements a purple background and white text. It also sets the margin property to "10px 0", which gives each div element a 10 pixel margin at the top and bottom.

The second and third style rules specify the properties of div elements with the respective class names a, b, and c. Each of these rules assigns a specific value to the max-width property. div.a has a maximum width of 120 pixels, while div.b and div.c each have a maximum width of 220 pixels. This means that div.a will never exceed 120 pixels in width, while div.b and div.c will never exceed 220 pixels.

Each div element will have a purple background, white text, and a top and bottom margin of 10 pixels when this code is rendered in a web browser. The first div with class name a will have a maximum width of 120 pixels, while the second and third div elements with class names b and c will have maximum widths of 220 pixels and 220 pixels, respectively.

As you can see from the above example, if the content width is greater than the defined maximum width, then the remaining content continues getting wrapped to the next line.

CSS max-width syntax

The syntax of the max-width property in CSS is:

max-width: x;

The value of x should be any of the following:

CSS Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!