What is the meaning of `auto` value in a CSS property.

The value of said property is adjusted automatically according to the content or the context of the element.

For example, a block-level element with height: auto will grow taller as it contains more text. For another example, a block element with margin: 0 auto will have the left and right margins increased until it becomes centered along the y-axis of the viewport.

It really depends on the property you give the value to, different properties behave differently depending on the content and context.


It depends. Here are some common usages of the auto value.

Height: auto

the element height depend upon the height of its children.

.container {
  width: 250px;
  height: auto;
  background: gray;
}

.item {
  width: 50px;
  background: orange;
}
<div class="container">
  <div class="item">
    child content
  </div>
</div>

Width: auto

for block level element the width is the container width subtracted the element's horizontal spacing (margin+border+padding).

.container {
  width: 250px;
  height: 150px;
  background: gray;
}

.item {
  width: auto;
  margin: 0 10px;
  border-left: 5px solid;
  border-right: 5px solid;
  padding: 0 10px;
  background: orange;
  font-size: 14px;
}
<div class="container">
  <div class="item">
    calculated content width is 200px
  </div>
</div>

note that the behaviour is different when the container is flex with align.

.container {
  width: 250px;
  height: 150px;
  display: flex;
  flex-direction: column;
  background: gray;
}

.item {
  width: auto;
  background: orange;
  /* comment out next line to make width take parent's width */
  align-self: start;
}
<div class="container">
  <div class="item">
    child
  </div>
</div>

Margin: auto

center a block level element horizontally.

.container {
  width: 250px;
  height: 150px;
  background: gray;
}

.item {
  width: 32px;
  margin: 0 auto;
  background: orange;
}
<div class="container">
  <div class="item">
    child
  </div>
</div>

push an element to the end inside flex container.

.container {
  width: 300px;
  height: 150px;
  display: flex;
  background: gray;
}

.item {
  width: 50px;
  height: 25px;
  background: orange;
  border-left: 1px solid;
}

.item3 {
  margin-left: auto;
}
<div class="container">
  <div class="item">
    child 1
  </div>
  <div class="item">
    child 2
  </div>
  <div class="item item3">
    child 3
  </div>
</div>

auto means automatically adjusted. The most common reason I use auto is:

margin: 0 auto;

to center an element.

Please note: if size is not declared, then it won't work.

Example 1: div is not centered, auto does not work

<style>
    .cont {
        margin: 0 auto;
    }
</style>
<div class="cont"></div> 

Example 2: div is centered to the page

<style>
    .cont {
        width: 1000px;
        margin: 0 auto;
    }
</style>
<div class="cont"></div> 

Tags:

Css