The CSS Width and Height Properties

How to use the width, and height (including min- and max-) properties of CSS.

1345 views

Edited: 2017-02-07 16:56

An element's width and height can be controlled with the: width, min-width, max-width, height, min-width, and max-width CSS properties.

The CSS min-width property is used to give elements a minimum width. When min-width is used in combination with percentages, this tells the browser that an element should not be narrower than the minimum width.

Below is an example of how to apply widths:

#WidthControl {
  min-width:300px;
  width:80%;
  max-width:1600px;
}

Creating responsive layouts

In responsive website layouts, a min-width makes sure that a website will not be narrower than a certain fixed width, specified in pixels. Today, all modern browsers support these properties.

In responsive layouts, most often we will want to leave the height on auto, while only specifying the width'(s) of our elements.

Having a single wrapper, called WidthControl, for the whole web page, will make it easier to control the width for all devices. We can then change how other elements behave in smaller browser windows via CSS media queries.

A simple wrapped layout:

<html>
 <head>
   <style type="text/css">
    #WidthControl {min-width:300px;width:80%;max-width:1600px;}
   </style>
 </head>

 <body>
  <div id="WidthControl">   
  </div>
 </body>
</html>

Doing this already ensures that our website will work in most devices. However, since a website usually has 2 or more columns, this will often not be enough. Also since some elements, mainly ads and images, will have a fixed width (in pixels).

To solve this problem, we must change how these elements should behave in lower screen resolutions and window sizes.

For images it is very easy. We can simply apply a percentage as max-width via media queries. This will ensure that an image will only start resizing once the image will no longer fit. For ads it is much harder, and we might be forced to hide them via display:none;

You may want to give your images a max-width even before you start using media queries. And give it some room for margins, too. I.e.:

#MainContent img {
  max-width:95%;
}

Adsense offers a responsive unit, but it is not truly responsive, and will not resize if a user resizes the browser window. This causes the ads to overlap. See also: Resizing Adsense Units When the Window Resizes

Properties

widthControls the actual width of an element.
heightControls the actual height of an element.
min-widthControls the minumum width of an element.
max-widthControls the maximum width of an element.
min-heightControls the minimum height of an element.
max-heightControls the maximum height of an element.

Possible Values

See Length units in HTML and CSS to understand the many possible values.

Tell us what you think: