CSS margin:auto - How does it work? A complete guide to using negative margins in CSS.

Using margin:auto to center a block element horizontally is a well-known technique. But have you ever wondered how it works?

The effect of auto depends on the element type and context. For top padding CSS auto can mean one of two things: take everything free space or 0 pixels. Depending on this, a different structure will be specified.

"auto" - occupy all available space

This is the most common way to use auto for indentation. If we set auto for the left and right padding of one element, they will evenly take up all the horizontal space available in the container. This will position the element in the center.

View example

This only works for horizontal padding. But won't work for floating and inline elements. And also for absolutely and fixedly positioned elements.

Simulate floating behavior by allocating available space

auto distributes all free space equally between the right and left margins. But what happens if we set this value for only one of the paddings? Then it will take up all the available space, and the element will be offset to the right or left edge.

View example

“auto” — set 0 pixels

As mentioned above, auto doesn't work for floated, inline, or absolutely positioned elements. They already have a structure defined, so there is no point in using margin auto.

This will only disrupt the original structure. Including CSS for indenting text at the top. Therefore, auto will set the padding of these elements to 0 pixels.

auto won't work for standard either block element, if no width is specified for it. In all the examples I gave, the elements had a width specified.

The value auto will define a padding of 0 pixels when the width of a block element is set to auto or 100% . Typically it takes up the entire width of the container, so there will be 0 pixels left for the padding width.

What happens to vertical padding when set to auto?

auto for both CSS top padding and bottom padding is always calculated as 0 pixels ( excluding absolutely positioned elements). The W3C specification states the following:

"If 'margin-top' or 'margin-bottom' is set to 'auto', they are set to 0."

This is due to the fact that on a web page, all elements are most often distributed vertically. Therefore, by centering an element height in a container, we will not achieve the fact that it will appear vertically centered relative to the page itself, as happens with horizontal centering.

Or maybe it's for the same reason that they decided to add an exception for absolutely positioned elements that can be centered vertically relative to the overall page height.

Or because the effect of combining indents (merging indents of adjacent elements). This is another exception to of this rule determining vertical offsets.

Centering absolutely positioned elements

Since there is an exception for absolutely positioned elements, you can use auto to center them vertically and horizontally. But first we need to figure out when margin:auto will work exactly like this for CSS top padding.

Another W3C specification says:

“If all three positions (“left”, “width” and “right”) are set to “auto”, first set “margin-left” and “margin-right” to 0...
» If "auto" is specified only for "margin-left" and "margin-right", then solve the equation with additional condition so that both paddings have the same width."

The situation regarding the auto value for horizontal padding is described here in some detail. To ensure that these paddings are the same size, left , width , and right should not be set to auto ( their default value). To center an element horizontally, you need to set the width of the absolutely positioned element to a certain value, and left and right must have equal values.

In the specification also mentioned something similar for the top padding of the CSS div.

"If 'top', 'height' and 'bottom' are set to 'auto', set 'top' to static..."

"If one of the three positions is not set to 'auto': If 'top' and 'bottom' are set to 'auto', solve the equation with an additional condition to set these paddings to the same values."

Therefore, to vertically center an absolutely positioned element, top , height and bottom must not be set to auto .

Now, putting all this together, we get the following:

View example

Conclusion

If you need to move an element on a page to the right or left without container elements ( for example, as in the case of float), remember that you can use auto for indentation.

Converting an element to absolutely positioned only to center it vertically ( top padding CSS), Not best idea. There are other options such as flexbox and CSS transform that are better suited for this.

Translation of the article " CSS – margin auto – How it Works"was prepared by the friendly project team.

Good bad

June 14, 2011 at 5:48 pm

Let's talk about margin, aka margin (part 1)

  • CSS

Seeing when beginners, while laying out page after page, make a bunch of mistakes, indenting margins and not fully understanding how this very margin actually works, I decided to write this article.

It will definitely be useful for beginning layout designers, but I doubt it for professionals, since a person who has been involved in layout for several years is already obliged to “memorize” all the features of this property by heart.

In this part of the article I will write about the vertical margin. We'll talk about horizontal in the next part.

To begin with, let's briefly look at what units of measurement there are, what they mean and which margins to use for indentation.

Cm, mm, inch, pc, ptabsolute units measurements. Recommended for use when printing documents.

Px, em, ex, % - relative units, are used for monitors.

For margin, I use px And % , A em– to specify font sizes. Ex (in IE ex = em / 2) – I do not recommend using it, because it is interpreted differently in each browser.

And in general, in what unit would you specify the indentation or font size: the browser converts everything into pixels, without taking into account the viewing area.

The viewing area is where the user sees the content of the site without scrolling the screen. It is different for each user.

Every layout designer knows that any element can be represented in the form of 4 areas (margin, border, padding and content).

Margin – margin. The construction of margins is different vertically and horizontally.

As I already wrote above, the dimensions for the margin can be set in em, ex, px - a rigid setting, and in % - they are calculated relative to some area.

I will give an example of one of the common mistakes made by beginning layout designers.

There are 2 divs: first and second divs.


#first(
padding: 100px;
background: #b5bcbc;
}
#second(
height: 100px;
background: #b06b48;
margin: 30% 0 0;
}

Please note that I did not set the width property to any div (we'll talk about this later). Now we are only interested in the margin, which is equal to margin: 30% 0 0;

I hope everyone knows how margin is considered in in this case, just in case, let me remind you that it is calculated clockwise, that is: the margin on top will be 30%, on the right - 0, on the bottom - 0 and on the left - since I didn’t specify anything, the margin takes the value of the opposite side, that is, in this case, if the margin on the right is 0, then the margin on the left, if not specified, is also 0.

But now we are interested in the margin, which is equal to 30%, also known as the top indent. Where does this 30% come from?

Many people believe and believe incorrectly that 30% is taken from the top of the entire page.


But this is not true!

Since in this case, the second div is nested within the first div, then margin-top:30% will be calculated relative to the width of the parent div second, that is, relative to the width of the first div!


In this case, the width of the first div is auto by default, so the div takes all the free space in width, and from this width the 30% margin top for the second div will be calculated.

When the parent div is made smaller, the top padding of the second div will also be reduced.

Margin can also be negative. In this case, the element vertically allows another element to “ride” onto itself or “move down” beyond the boundaries of its container.

For example: two divs lying one below the other.


if we add margin-bottom: -100px to the first div, and margin-top: -50px to the second
#first(
height: 200px;
background: #69c;
margin: 0 0 -100px;
}
#second(
height: 200px;
background: #f60;
margin: -50px 100px 0;
}

Then the following will happen.


But... this is where the big mistake newbies make.

Many people think that since the top div has a margin bottom of -100px, and the bottom div, margin top -50px, then the bottom div will “override” the top one by -150px.

If the margins are of the same name (both margins are either negative or positive number), then in this case it is taken big number modulo, and less is not taken into account.

In this case, the bottom div will overlap the top div by 100px, and 50px will not be taken into account.

The same is true for positive margins, the bottom div will “move” away from the top one by 100px, and 50px will not be taken into account.

Consider the following example.
There are 2 divas, one below the other.


#first(
height: 200px;
background: #69c;
margin: 0 0 -100px;
}
#second(
height: 200px;
background: #f60;
margin: 50px 100px 0;
}

First
second

As you see, the margin bottom of the first one is negative, and the margin top of the second one is positive, what will happen in this situation?

For opposite margins, addition will occur, that is: -100 + 50 = -50. Accordingly, the bottom div will move up 50px.

Two divs, one nested inside the other.


#first(
background: #b5bcbc;
}
#second(
height: 200px;
background: #b06b48;
}

If you add a margin top of 200px to the inner div,
#second(
height: 200px;
background: #b06b48;
margin-top: 200px;
}

Well, here is another mistake! Some people believe that the inner margin should “move” 200px down from its parent, while its parent will remain in place, and thereby stretch.


But, no matter how it is!

If the parent element does not have limiting factors (I will write about these factors below), then the margin moves from the internal element to the external one. Then by old scheme a margin is selected: if they are of the same name, then the larger one is selected, if they are opposite, then addition occurs.
And the result


But what if we don’t need this and want the parent div to remain in its place, and the child div to move 200px down?

You can cancel this action in relation to the parent; there are several ways.
1. assigning padding to the parent block
2. setting border to the parent block
3. setting overflow to the parent block, any value except visible (works everywhere except old IE)
And voila


Thank you for your attention, I hope I was able to clarify for beginners what margin is and how to calculate it correctly and from where.
If the article was useful and you want to read the continuation, then in the next part I will describe horizontal margins. Things there are not as simple as they seem at first glance ;)

There are several points of view on the use negative margins in CSS, both sharply negative and purely positive.

Negative field in CSS rule as follows:

CSS

#content (margin-left:-100px;)

Negative fields are usually used in small doses, but as you will see later, they can do more. There are a few things you need to know about negative margins (to avoid typing mistakes):

  • Validity in css
    The W3C tells us: “Negative values ​​for margin properties it is permissible to use." More details at www.w3.org/TR/CSS2/box.html#margin-properties
  • Negative margins are not HACK
    This comes from misunderstanding and from external influence negative margin for layout. The only time a negative margin can become a hack is when you are trying to fix a bug in your code using a negative margin.
  • Impact on Flow
    Negative margins do not break flow when applied to “non-floating” elements. That is, if you use a negative margin to push an element up, then all subsequent elements will also be pushed up.
  • Different reaction when used in conjunction with float
    Negative margins are still not everyday CSS, so you should use such margins with caution.
  • Some problems dreamweaver
    There is nothing to discuss here.
  • Full compatibility
    Negative margins are supported by all browsers, including IE6.

Working with negative margins (margin)

Negative margins are very powerful when used correctly.


The image shows how static element reacts to negative fields.

  • When a static element receives a negative top/left margin, the element “moves” in the specified (top/left) direction.

    CSS

    /* Element moves 10px up */ #mydiv1 (margin-top:-10px;)
  • But if you use it for down/right, then the element will not move in the down/right direction as you assume. Instead, this will push the subsequent element into the main element, overlapping it.

    CSS

    /* All subsequent elements behind #mydiv1 will move up 10px, but #mydiv1 itself will not move */ #mydiv1 (margin-bottom:-10px;)
  • If an element does not have a width specified, then using a negative margin in the left/right direction will push the element in both directions as the element's width increases.

    CSS

    #mydiv1(margin:0 auto -20px; height: 150px; /*...*/) #mydiv2(margin:0 auto; height: 150px; /*...*/)

Negative margin for floating elements

Consider the following markup:

HTML

First
Second
  • If a negative margin is applied to a floated element, it creates space that causes the content to overlap. This is great for fluid layouts where one column is 100% wide and the other column is e.g. fixed width at 100px .

    CSS

    #mydiv1 (float:left; margin-right:-100px;)
  • If both elements are float:left and #mydiv1 has margin-right:-20px , then #mydiv2 treats #mydiv1 as if it were 20px less than its actual width (thus overlapping it). Interestingly, the #mydiv1 content does not respond to these manipulations and retains its current width.
  • If the negative margin is equal to the actual width, then the overlap will be complete. This happens because margins, padding, borders, and width are added to the actual width of the element. So if the negative margin is equal to the total width of all the above properties, then the actual width of the element becomes 0.

Effective techniques based on the use of negative margin

Ever since we learned that there is a negative field valid code, several useful CSS technician based on this technique.

If you have a list with so many items that it doesn't make sense to display them vertically, why not divide the list into three columns?


Negative margins will handle this without using any additional tags or the float property. It's amazing how easy it is to split a list into three columns, like this:

HTML

  • Eggs
  • Ham
  • Bread
  • Butter
  • Flour
  • Cream

Seeing when beginners, while laying out page after page, make a bunch of mistakes, indenting margins and not fully understanding how this very margin actually works, I decided to write this article.

It will definitely be useful for beginning layout designers, but I doubt it for professionals, since a person who has been involved in layout for several years is already obliged to “memorize” all the features of this property by heart.

In this part of the article I will write about the vertical margin. We'll talk about horizontal in the next part.

To begin with, let's briefly look at what units of measurement there are, what they mean and which margins to use for indentation.

Cm, mm, inch, pc, pt– absolute units of measurement. Recommended for use when printing documents.

Px, em, ex, %- relative units, used for monitors.

For margin, I use px And % , A em– to specify font sizes. Ex (in IE ex = em / 2) – I do not recommend using it, because it is interpreted differently in each browser.

And in general, in what unit would you specify the indentation or font size: the browser converts everything into pixels, without taking into account the viewing area.

The viewing area is where the user sees the content of the site without scrolling the screen. It is different for each user.

Every layout designer knows that any element can be represented in the form of 4 areas (margin, border, padding and content).

Margin – external indent. The construction of margins is different vertically and horizontally.

As I already wrote above, the dimensions for the margin can be set in em, ex, px - a rigid setting, and in % - they are calculated relative to some area.

I will give an example of one of the common mistakes made by beginning layout designers.

There are 2 divs: first and second divs.


#first(
padding: 100px;
background: #b5bcbc;
}
#second(
height: 100px;
background: #b06b48;
margin: 30% 0 0;
}

Please note that I did not set the width property to any div (we'll talk about this later). Now we are only interested in the margin, which is equal to margin: 30% 0 0;

I hope that everyone knows how the margin is calculated in this case, just in case I’ll remind you that it is calculated clockwise, that is: the top margin will be 30%, the right - 0, the bottom - 0 and the left - since I didn’t indicate anything , then the margin takes the value of the opposite side, that is, in this case, if the margin on the right is 0, then the margin on the left, if not specified, is also 0.

But now we are interested in the margin, which is equal to 30%, also known as the top indent. Where does this 30% come from?

Many people believe and believe incorrectly that 30% is taken from the top of the entire page.


But this is not true!

Since in this case, the second div is nested within the first div, then margin-top:30% will be calculated relative to the width of the parent div second, that is, relative to the width of the first div!


In this case, the width of the first div is auto by default, so the div takes all the free space in width, and from this width the 30% margin top for the second div will be calculated.

When the parent div is made smaller, the top padding of the second div will also be reduced.

Margin can also be negative. In this case, the element vertically allows another element to “ride” onto itself or “move down” beyond the boundaries of its container.

For example: two divs lying one below the other.


if we add margin-bottom: -100px to the first div, and margin-top: -50px to the second
#first(
height: 200px;
background: #69c;
margin: 0 0 -100px;
}
#second(
height: 200px;
background: #f60;
margin: -50px 100px 0;
}

Then the following will happen.


But... this is where the big mistake newbies make.

Many people think that since the top div has a margin bottom of -100px, and the bottom div, margin top -50px, then the bottom div will “override” the top one by -150px.

If the margins are of the same name (both margins or a negative or positive number), then in this case the large absolute number is taken, and the smaller one is not taken into account.

In this case, the bottom div will overlap the top div by 100px, and 50px will not be taken into account.

The same is true for positive margins, the bottom div will “move” away from the top one by 100px, and 50px will not be taken into account.

Consider the following example.
There are 2 divas, one below the other.


#first(
height: 200px;
background: #69c;
margin: 0 0 -100px;
}
#second(
height: 200px;
background: #f60;
margin: 50px 100px 0;
}

First
second

As you see, the margin bottom of the first one is negative, and the margin top of the second one is positive, what will happen in this situation?

For opposite margins, addition will occur, that is: -100 + 50 = -50. Accordingly, the bottom div will move up 50px.

Two divs, one nested inside the other.


#first(
background: #b5bcbc;
}
#second(
height: 200px;
background: #b06b48;
}

If you add a margin top of 200px to the inner div,
#second(
height: 200px;
background: #b06b48;
margin-top: 200px;
}

Well, here is another mistake! Some people believe that the inner margin should “move” 200px down from its parent, while its parent will remain in place, and thereby stretch.


But, no matter how it is!

If the parent element does not have limiting factors (I will write about these factors below), then the margin moves from the internal element to the external one. Then, according to the old scheme, a margin is selected: if they are of the same name, then the larger one is selected, if they are different, then addition occurs.
And the result


But what if we don’t need this and want the parent div to remain in its place, and the child div to move 200px down?

You can cancel this action in relation to the parent; there are several ways.
1. assigning padding to the parent block
2. setting border to the parent block
3. setting overflow to the parent block, any value except visible (works everywhere except old IE)
And voila


Thank you for your attention, I hope I was able to clarify for beginners what margin is and how to calculate it correctly and from where.
If the article was useful and you want to read the continuation, then in the next part I will describe horizontal margins. Things there are not as simple as they seem at first glance ;)