margin: auto; 你真的理解么?

今天在看《精通CSS高级web标准解决方案》看到一个例子,让我对margin:auto; 又有了深入的理解。

案例如下:

<!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>

在这里插入图片描述

解释:
通过flex布局的justify-content: flex-end; 我们可以将所有项移动到右侧。然后给第一个元素设置margin-right: auto;可以得到如上效果。

在我们工作中最常用的就是margin: auto; 让块元素水平居中,那么刚刚的margin-right: auto; 怎么就占满了整个空间呢?

下面我们来看一下margin的填充规则:

  1. 如果一侧定值,一侧auto,则auto为剩余空间大小
  2. 如果两侧均是auto,则平分剩余空间

当我将第一元素上的margin-right: auto; 设置成 margin: auto; 时, 则效果如下:
在这里插入图片描述

再来一个例子:

<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>

左边距是20px,右边距是80px。这里son宽度是200px,容器是300px,总剩余空间大小是100px,其中margin-right使用了80px,那么margin-left的‘auto’计算值就是剩余的20px了。

margin-left:auto代替float:right实现右对齐

.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配合绝对定位实现水平和垂直方向居中

.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>

参考书籍《CSS世界》

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

. . . . .

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值