margin: auto; Do you really understand?

Today I saw an example in "Mastering CSS Advanced Web Standard Solution", which gave me an in-depth understanding of margin: auto ;.

The case is as follows:

<!DOCTYPE html>
<html>
<head>
	<title></title>
	<style type="text/css">
		#box {
			width: 300px;
			border: 1px solid skyblue;
			display: flex;
			justify-content: flex-end;
		}
		.one {
			background: red;
			margin-right: auto;
		}
		.two {
			background: green;
		}
		.three {
			background: blue;
		}
	</style>
</head>
<body>
	<div id='box'>
		<div class="one">one</div>
		<div class="two">two</div>
		<div class="three">three</div>
	</div>

</body>
</html>

Insert picture description here

Explanation:
With justify-content: flex-end; of flex layout, we can move all items to the right. Then set margin-right: auto; to the first element to get the above effect.

The most commonly used in our work is margin: auto; to center the block elements horizontally, so how did the margin-right: auto; just occupy the entire space?

Let's take a look at the filling rules of margin:

  1. If one side is set and one side is auto, then auto is the remaining space
  2. If both sides are auto, the remaining space is divided equally

When I set margin-right: auto; on the first element to margin: auto ;, the effect is as follows:
Insert picture description here

Another example:

<style>
    .father {
      width: 300px;
      background-color: #f0f3f9;
    }
    .son {
      width: 200px;
      height: 120px;
      margin-right: 80px;
      margin-left: auto;
      background-color: #cd0000;
    }
  </style>

<div class="father">
    <div class="son"></div>
  </div>

The left margin is 20px and the right margin is 80px. Here the width of the son is 200px, the container is 300px, and the total remaining space is 100px. Among them, margin-right uses 80px, then the margin-left calculation of "auto" is the remaining 20px.

margin-left: auto instead of float: right to achieve right alignment

.father {
      width: 300px;
      background-color: #f0f3f9;
    }
    .son {
      width: 200px;
      height: 120px;
      margin-left: auto;
      background-color: #cd0000;
    }

<div class="father">
    <div class="son"></div>
  </div>

magin: atuo cooperates with absolute positioning to achieve horizontal and vertical centering

.father {
      width: 300px;
      height: 150px;
      background-color: #f0f3f9;
      position: relative;
    }

    .son {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 200px;
      height: 100px;
      background-color: #cd0000;
      margin: auto;
    }


<div class="father">
    <div class="son"></div>
  </div>

Reference book "CSS World"

Published 398 original articles · Liked 182 · Visits 370,000+

Guess you like

Origin blog.csdn.net/yexudengzhidao/article/details/105326075