All about the auto keyword in CSS

CSS has a keyword autothat you can use when working with various properties of elements. These are properties that affect the position, height, and width of elements. These are properties designed to adjust the indentation of elements and their other characteristics. I had a desire somewhere to record everything that I know about auto. For example, to arrange this all in the form of material that could become a reference for those who are interested in the intricacies of using this keyword.

The keyword autohas special meaning when used with various CSS properties. We will analyze the features autoregarding the application of this value to various properties. Here, first of all, we will be interested in the technical details of the work.



auto. We will also talk about how to get the most out of using this property. Here you will find notes on use autocases and examples.

Width property: auto


The initial width of block elements, such as <div>or <p>, is the value auto. This leads to the fact that such elements occupy the entire horizontal space of the block containing them.

“Width of the block containing the element” is, in accordance with the CSS specification, a value calculated by the following formula:

margin-left’ + ‘border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ + ‘margin-right

When the width of the element specified value auto, it can be configured such properties as margin, padding, borderand it is, thus, will not be greater than its parent element. The width of the block restricting the contents of the block element will be the size of the content minus the width of its parts defined by the properties margin(field, outer indent), padding(inner indent) and border(border).


Comparison of width: auto and width: 100%

Consider, as an example, the device features of the above layouts.

Here is the HTML markup:

<div class="wrapper">
  <div class="item"></div>
</div>

Here is the CSS:

* {
    box-sizing: border-box;
}

.wrapper {
      max-width: 600px;
      margin: 2rem auto 0;
      padding: 1rem;
}

.item {
      padding: 1rem;
      margin: 0 50px;
      border: 15px solid #1f2e17;
}

Here everything looks as it should, the content is limited to the parent element.


The element is within the parent element.

And what happens if you specify that the width of the element (width) should not be specified as a valueauto, but how100%? With this approach, the element will occupy 100% of the width of the parent element, to which the space allocated to the right and left margins will be added. Here is the appropriate style:

.item {
      width: 100%;
      padding: 1rem;
      margin: 0 50px;
      border: 15px solid #1f2e17;
}

But what happens after applying it to an element.


The element extends beyond the parent element (text direction is ltr).

The element is wide568px . It is calculated as follows:

border-left-width’ + ‘padding-left’ + ‘width’ + ‘padding-right’ + ‘border-right-width’ = 15 + 16 + 506 + 16 + 15 = 568px

If the property is directionset to a value ltr, then the value margin-rightwill be completely ignored. In our case, this is exactly what happens. However, if directionrecorded rtl, will be ignored margin-left.


The element goes beyond the parent element (text direction is rtl).

Here you can experiment with the example code.

▍ Use cases for width: auto


In order to properly understand the meaning auto, not enough story about the basics. Therefore, I conducted some research aimed at showing scenarios for the practical use of the property width: auto.

Different widths of elements in mobile and desktop versions of the page



Mobile and desktop application options

There is a group of buttons. It is necessary that in the mobile version of the application they would be located next to each other (an element containing a button should occupy 50% of the parent element). In the desktop version of the application, each button should occupy the entire width of the parent container. How to do it?

Here is the HTML markup:

<div class="group">
    <div class="group__item">
        <button class="c-button">Sign In</button>
    </div>
    <div class="group__item">
        <button class="c-button c-button--ghost">Register</button>
    </div>
</div>

In order to place buttons next to each other in the mobile version of the page, I used the flexbox layout. Here is the relevant CSS:

.group {
    display: flex;
}

.group__item {
    width: 50%;
}

In the desktop version, I need the buttons to occupy the entire width of the parent element. There may be a temptation to use the design width: 100%. Truth? But there is a better solution:

@media (min-width: 800px) {
    /*    flexbox-    */
    .group {
        display: block;
    }

    .group__item {
        width: auto;
    }
}

Since .group__itemthis is a block element, use width: autoleads to the fact that this element perfectly fills with itself the space available in its parent element.

Here is a working version of this example.

Height property: auto


If we consider working with a property heightthat sets the height of the elements, then everything looks different. The height of the element, when applying the value auto, corresponds to the height of the content of the element.

Consider the following example:

<div class="wrapper">
  <div class="item">What's my height?</div>
</div>

In order for an element with a class to .itemoccupy the entire height of the container, you can use one of the following methods:

  1. You can set an element with a class a .wrapperfixed height, and then add a .itemproperty to the element style height: 100%.
  2. You can use the .wrapperflexbox layout for the element , so that the child .itemwill, by default, be stretched to the size of the parent element.

Here is the CSS:

.wrapper {
    height: 200px;
}

.item {
    height: 100%;
}


Parent and child elements

Fields and keyword auto


Fields (outer margins) are most often used for horizontal centering of elements whose width is known.

Consider an example.


The item to be centered. The

blue rectangle needs to be horizontally centered. For this purpose, you can use the following style:

.element {
    margin-left: auto;
    margin-right: auto;
}

Turning to the CSS specification:

If the 'margin-left' and 'margin-right' properties are set to 'auto', the width of the margins is the same. This leads to the horizontal alignment of the element relative to the edges of the block including it.


The fields of an element are the same width.

Here is a demo of this example.

▍Use of margin: auto property for absolutely positioned elements



Centered Element

Another, less common, scenario for applying a valueautois to center absolutely positioned elements using a constructmargin: auto. If there is an element that needs to be centered inside the parent element both horizontally and vertically, it may seem that you need to use thetranslateXorproperty for thistranslateY.

In order for the property tomargin: autoallow us to properly align the element, the following conditions must be met:

  1. The width and height of the element are specified.
  2. The property of the element is set position: absolute.

Here is the HTML markup:

<div class="wrapper">
  <div class="item">I am centered.</div>
</div>

Here is the style code:

.wrapper {
    position: relative;
}

.item {
    width: 200px;
    height: 100px;
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
}

Here is a demonstration of this alignment technique.

Flexbox layouts and auto field customization


Using automatically configured fields can, in some cases, prove to be a very useful trick. If the child element has a field whose dimensions are set using the value auto, it will be maximally shifted in the parent element to the side opposite to the configured field. For example, if a property is assigned to a flex element margin-left: auto, it will be shifted to the right as much as possible.

Let's look at the following layout. There are two rectangular child elements located in the parent flexbox element.


A pair of elements in a flexbox container

We need element # 2 to be moved to the right border of the container. Using the valueautofor the property isgreatfor thismargin-left:

.wrapper {
    display: flex;
}

.item-2 {
    margin-left: auto;
}

Here's what happened after applying this style.


Element number 2 is moved to the right edge of the container.

It should be noted that this technique also works with the elements being vertically aligned. In this example, apply the following style of element # 2:

.item-2 {
    margin-top: auto;
}

Here is the result.


Element No. 2 is moved to the lower edge of the container.

In addition, if there is only one child element, then in order to align it both horizontally and vertically, you can use the propertymargin: auto. Suppose that in the container there is only element number 1, which needs to be aligned just like that. To do this, we use the following style:

.item-1 {
    margin: auto;
}

This is enough to center the element.


Item # 1 centered on the container

▍Flex property and auto value


When developing flexbox layouts, you can use the property for child elements flex: auto. What does this design mean? The fact is that when a child element has a property flex: auto, this is equivalent to the fact that the element is assigned a style flex: 1 1 autosimilar to the following construction:

    .item {
        flex-grow: 1;
        flex-shrink: 1;
        flex-basis: auto;
    }

Here is what MDN says about this : “The dimensions of an element are determined according to its properties widthand height, but the element can be stretched, taking up additional free space available in the flex container. An element, in order to fit in a container, can and is compressed to its minimum size. This is similar to setting style flex: 1 1 auto. ”

In other words, the size of the element with the property flex: autowill be set based on its width and height. But this element can stretch or contract depending on how much space is available to it in the container. I did not know about this until I started researching for this article.

As usual, consider an example.

Here is the markup:

<div class="wrapper">
  <div class="item item-1">Item</div>
  <div class="item">Item</div>
  <div class="item">Item</div>
</div>

Here are the styles:

.wrapper {
    display: flex;
    flex-wrap: wrap;
}

.item {
    width: 120px;
    height: 500px;
}

.item-1 {
    flex: auto;
}

And here is the result.


Using flex: auto

Here is a working version of this example.

Grid layouts and auto value


▍Use auto to adjust columns



Using the grid-template-columns: auto 1fr 1fr style

When developing grid layouts, you can use the valueautowhen setting up the columns. This will mean that the width of the columns will depend on the size of their contents. Here is what I mean:

.wrapper {
    display: grid;
    grid-template-columns: auto 1fr 1fr;
}

▍Grid layouts and using auto value to set fields


When using grid layouts, the value autocan be used to customize the element fields. This is done to obtain results similar to those achieved when used autoin Flexbox layouts. If we are working with a grid layout, and one of the grid elements has, for example, a style margin-left: auto, it will be moved to the right side of the layout, and its width will be selected based on the size of its contents.

Consider the following example.


Grid layout

We need the width of an element toItem 1depend on its content, and not on the grid space available to it. To do this, we can use the following style:

    .item-1 {
        margin-left: auto;
    }

Here is the result of applying this style.


The width of an element depends on its content.

▍RTL layouts


It is worth noting that the use of properties margin-left: autoor margin-right: autoshows itself well for LTR-layouts (for layouts in which the content is located from left to right), for example, for those that are used to display texts written in English. But be aware that on multilingual sites these meanings are reversed. Even better, and I would recommend doing just that, using Flexbox- or Grid-properties in such mock-ups, doing this in cases where the goal can be achieved with their help. If this cannot be achieved with the help of such properties, resort to setting margin properties using autoonly as a last resort. Instead, it’s best to use the logical properties of CSS .

Overflow property


When working with elements of web pages, we need to know about the size of the content that these elements are capable of containing. If the content is more than what the element can contain, you need to show the scroll bar to work with such content.

To solve this problem, you can try to use the following style:

.element {
    overflow-y: scroll;
}

But with this approach, a scrollbar may appear even if the element displays content whose size does not exceed the size of the element. Here is an example.


Element to which the overflow-y: scroll style is assigned

In the Chrome browser on the Windows platform, the scroll bar is always displayed. This is an example of an element misbehaving that can confuse the user.

Using instead of this valueautoallows you to ensure that the scroll bar will be displayed only in cases where the height of the content exceeds the height of the container.

Thefollowing is statedon MDN : “Depends on the user agent. If the content is placed in the element area corresponding to the internal space of the element, it looks the same as the content displayed in the modevisiblebut this creates a new block formatting context. "Desktop browsers display scrollbars if the content is larger than the size of the item."

Properties for positioning elements


CSS-properties responsible for positioning of elements, such as top, right, bottomand left, the value is maintained auto. What I want to talk about now, I learned during the writing of this article.

Consider the following layout.


Demo Layout

There is a parent element with a customized propertypaddingthat defines the indentation. This element has another element, a child. The child element is absolutely positioned, but its properties, which are responsible for positioning, are not configured. Here are the styles:

.wrapper {
    position: relative;
    padding: 16px;
}

.item {
    position: absolute;
    width: 100px;
    height: 100px;
}

The fact is that in CSS, each property has a certain initial value (the default value). If you examine a child element and look at the computed styles, then what will be the value of its property left?


Examining the computed styles of the child.

The default value for the propertyleftis this16px. Where did it come from if we didn't even ask him? The reason for this is that the properties of an absolutely positioned element are consistent with its closest parent whose property is setposition: relative. The parent element has a propertypadding: 16px. This causes the child to be placed 16 pixels from the top and left sides of the parent. Interesting, right?

Now you may have a question about what is the use of this for us. I propose to deal with this.

Imagine that a child needs to be placed in100pxfrom the left border of the parent element when viewing the page on small screens, and on large screens you can place the element where it would be located when applying the default values.

Here is a style suitable for small screens:

.wrapper {
    position: relative;
}

.item {
    position: absolute;
    left: 100px;
    width: 100px;
    height: 100px;
}

How to reset the property value leftwhen viewing a page on large screens? Moreover, the value left: 0here cannot be used, since this will lead to the fact that the child element is pressed to the edge of the parent element, but we do not need it. Take a look at the page layout shown below. He clarifies my point.


The child element does not behave properly.

To reset the positioning properties of the child element, you must use the constructleft: auto. This is stated on the MDN as follows: “An element is placed horizontally as it would have to be positioned if it were a static element.”

This means that when placing the element, the property of thepaddingparentelement will be taken into account, and it will be ensured that the child element does not “stick” to the edge of the parent element.

Here is the CSS:

.item {
    position: absolute;
    left: 100px;
    width: 100px;
    height: 100px;
}

@media (min-width: 800px) {
    .item {
        /*  -  left: 16px */
        left: auto;
    }
}

The same applies to a property top. The calculated values ​​of the rightand properties bottomset by default are equivalent, respectively, to the width and height of the element.

Here is a demo project for this section.

Examples of using the auto value


I must say right away that the examples given here do not cover all the possibilities of meaning auto, but I hope that what I tell you will come in handy.

▍ Tooltip arrow


When creating tooltips, they need to have an arrow pointing to the object the tooltip refers to. So these tips are more understandable. In the event that we are developing a design system, we need to provide for different states of prompts. For example, prompts with an arrow pointing to the left, and with an arrow pointing to the right.


Directional arrows pointing in different directions

.tooltip:before {
    /*   */
    position: absolute;
    left: -15px;
}

/*    ,   */
.tooltip.to-right:before {
    /*   */
    position: absolute;
    left: auto;
    right: -15px;
}

Note that I used the property left: autoto override the property left: -15pxin the original implementation. And so you know, this is used quite often. Therefore, I would recommend using the following instead of the above approach:

.tooltip:before {
    position: absolute;
    right: 100%;
}

.tooltip.to-right:before {
    /*   */
    position: absolute;
    right: auto;
    left: 100%;
}

Using a value 100%, we avoid using a hard-set value (arrow width), which can lead to malfunctioning of the system if the arrow size changes. This solution is better suited to possible future changes.

▍ Component Card


Perhaps your project has a component card on which, in the upper left corner, is some kind of icon. It can play a decorative role, or it can be a button for performing an action. Regardless of the role of the icon, the components need to be designed so that the icon can be positioned both in its upper left corner and in its upper right corner. Here is how it looks.


Component card with an icon that is located in different angles

Using a property,left: autoyou can easily reset the value of the property specified in its basic implementation. Here is the CSS:

.card .icon {
    position: absolute;
    left: 15px;
    top: 15px;
}

.card.is-right .icon {
    left: auto;
    right: 15px;
}

▍Flexbox layouts and value of auto margin property


Flexbox layouts give web developers truly endless possibilities. By combining the capabilities of such layouts with fields, the value of which is used to configure them auto, we can create very powerful layouts.

Consider the following example.


Automatic adjustment of element fields

There is a vertical container containing the element title, its description and button located on the right. We need the button to be attached to the right side of the container.

Here is the markup:

<div class="item">
    <div class="item-group">
        <!--    -->
    </div>
    <button class="item__action">Confirm</button>
</div>

Here are the styles:

    .item {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
    }

    .item__action {
        margin-left: auto;
    }

Done! Using the property margin-left: autoallows you to place the button in the upper right corner of the element. What's even nicer is that we can use logical CSS properties if we are developing a multilingual site. The CSS will be something like this:

.item__action {
    margin-inline-start: auto;
}

If you want to know more about RTL styling, here is a useful resource dedicated to this topic.

▍Grid layouts and auto margin value


By adjusting the fields of Grid elements, you can set fixed and percentage values, and also - you can use the value auto. I am particularly interested in the meaning auto. Take a look at the following layout.


Grid layout

Here is a fragment of the markup:

<p class="input-group">
    <label for="">Full Name</label>
    <input type="email" name="" id="">
</p>

Here are the styles:

.input-group {
  display: grid;
  grid-template-columns: 1fr;
  grid-gap: 1rem;

  @media (min-width: 700px) {
    grid-template-columns: 0.7fr 2fr;
  }
}

I would like to align the labels, elements label, on the left edge of the fields for entering data (elements input). In order to do this, you need to apply the following style:

.input-group label {
    margin-left: auto;
}

Applying this style will result in the result shown in the following figure.


Left-aligning captions for data entry

▍ Design of modal windows



Modal window

When working on the design of modal windows, it is important to consider that the contents that need to be displayed in the window may not fit entirely into it. In order for the window to work normally in this situation, you can use the following style:

.modal-body {
    overflow-y: auto;
}

Thanks to this style, the scroll bar appears only if the contents of the window are large enough.

Summary


In this article, we examined the features of applying the keyword autoin CSS. We hope you find it useful what you read today.

Dear readers! In what situations do you use value autoin CSS?


All Articles