HTML & CSS - - By Guy Routledge

AtoZ CSS Quick Tip: How to Use the CSS Auto Value

Buying a SitePoint Premium membership will give you access to the full AtoZ: CSS series.

Loading the player…

Welcome to our AtoZ CSS series! In this series I’ll be exploring different CSS values (and properties) beginning with a letter from the alphabet. In this article I’ve added a new quick tip/lesson about the auto property for you.

A is for auto

The auto CSS value is very useful in automatically adjusting your content to fit within your webpage. There is a multitude of uses for the value – you can use it to contain overflow content, as an alternative to clearfix, keeping images in proportion or even centering the content in the page. I’ll teach you through how to do this with these three easy tips.

Tip 1

The auto value is really useful when it is possible that content may flow outside of its containing element. Setting overflow: auto will add a scroll bar when required to keep the content within the containing element.

.content-box {
  width: 300px;
  height: 300px;
  border: 1px solid #cc3f85;
  overflow: auto;
}

See the Pen CSS A to Z: A — Overflow Tip 1 by SitePoint (@SitePoint) on CodePen.

Test the above CodePen snippet by removing the overflow property and watch what happens to the content that does not fit into the containing box.

Tip 2

overflow: auto can also be used as an alternative to clearfix. This creates a new block formatting context which contains the floats and prevents container collapse. In some cases this may be a better alternative to using overflow: hidden.

.container {
  width: 600px;
  border: 4px solid #9be22d;
  overflow: auto;
}

.blue-box {
  float: left;
  width: 200px;
  height: 200px;
  background-color: #66d9ef;
}

.pink-box {
  float: right;
  width: 200px;
  height: 200px;
  background-color: #cc3f85;
}

See the Pen CSS A to Z: A — Overflow Tip 2 by SitePoint (@SitePoint) on CodePen.

Test the above CodePen snippet by removing the overflow property and watch how the containing element collapses.

Tip 3

The auto value can also be used to keep images in proportion.

If you need to resize an original image within a containing element, only explicitly set either the width or height (in relation to the containing element) and set the other element to auto. This will keep the image in proportion and avoid any distortion.

.image-holder {
  width: 50%;
  border: 1px solid;
}

img {
  width: 40%;
  height: auto;
}

See the Pen CSS A to Z: A — Overflow Tip 3 by SitePoint (@SitePoint) on CodePen.

Test the above CodePen snippet by resizing your window and watch how the image stays in proportion.

Sponsors