margin-left: auto;为什么可以使元素靠右

本文深入解析了CSS中使用'margin-left:auto;'使div元素靠近浏览器右侧的原理,以及如何通过'margin:auto;'实现元素的水平居中。这涉及到CSS盒模型中各属性之间的计算规则。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

div {
  width: 100px;
  margin-left: auto;
}

上面的代码可以使得div靠近浏览器的右侧显示是为什么?

有点弱智的问题,竟然现在才知道...记录一下 

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' +'border-right-width' + 'margin-right' = width of containing block

你的属于其中一种情况:
If there is exactly one value specified as 'auto', its used value follows from the equality.

也就是在上述等式中,只有你设置的margin-left: auto,那么margin-left将会被设置为满足上述等式,而等式的右边是容器盒子宽度,等式中的其它值(除过width)都为0,因此margin-left = width of containing block - width(div)

再来看一下我们经常使用的 margin: auto 水平居中的原理。

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

转自知否  https://segmentfault.com/q/1010000008431088

``` <view v-if="currentTab === 3" class="list"> 11111 <!-- 查询条件容器 --> <view class="query-condition"> <!-- 标题 --> <text class="section-title" style="margin-left: 20rpx;">查询条件</text> <!-- 条件输入行 --> <view class="input-row"> <!-- 商家名称部分 --> <view class="input-group"> <text class="label">商家名称</text> <input class="input" type="text" placeholder="请输入" style="margin-left: 20rpx; width: 200rpx;" /> </view> <!-- 计费日期部分 --> <view class="date-group" style="margin-left: 40rpx;"> <text class="label">计费日期</text> <input class="date-input" type="month" style="margin-left: 20rpx; width: 200rpx;" /> <text style="margin: 0 10rpx;">至</text> <input class="date-input" type="month" style="width: 200rpx;" /> </view> <!-- 操作按钮 --> <view class="action-buttons" style="margin-left: auto;"> <button class="btn reset-btn" @click="handleReset" style="margin-right: 30rpx;" >重置</button> <button class="btn query-btn" @click="handleQuery" >查询</button> </view> </view> </view> </view>```查询条件 ,左上角(上左有点距离)然后中间内容:商家名称后面是个input可以选择的输入框,后面是 计费日期,可以选择几月到几月,有点距离跟前面的input,然后后面有俩个按钮重置和查询重置白色背景黑色字体,查询蓝色背景白色字体位置最靠有但也有点距离,按钮跟前两个都是在一行,这个是我要的位置,现在位置全乱了,可能是大小原因导致换行什么的,帮我改下
最新发布
04-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值