为什么margin自动适用于左/右,而不适用于顶部/底部?

编程入门 行业动态 更新时间:2024-10-28 09:14:21
本文介绍了为什么margin自动适用于左/右,而不适用于顶部/底部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我一直想知道为什么我可以对左边/右边使用margin auto来水平居中div,而不能垂直居中.在这里,我希望垂直居中: div-block-vertical-line ,但是margin-top和margin-bottom无效.

I always wanted to know why I can use margin auto for left/right to horizontally center a div, and not for vertically center. Here I would have liked to vertically center : div-block-vertical-line but margin-top and margin-bottom won't work.

.div-block-container { width: 2%; height: 300px; background: red; } .div-block-vertical-line { display: block; width: 2px; height: 90%; margin-right: auto; margin-left: auto; margin-top: auto; margin-bottom: auto; background: blue; }

<div class="div-block-container"> <div class="div-block-vertical-line"></div> </div>

推荐答案

如果您选中"MDN"页面:

自动

浏览器选择合适的边距使用.例如,在在某些情况下,该值可用于使元素居中.

The browser selects a suitable margin to use. For example, in certain cases this value can be used to center an element.

因此,如果您使用 auto ,则浏览器只需选择 0 作为上/下边距.

So your browser will simply select 0 for top/bottom margin if you use auto.

以及规范:

如果'margin-top'或'margin-bottom'为'auto',则其使用值为0

If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0

您要查找的内容在 flexbox模型中定义:

弹性项目上的自动边距效果与自动边距非常相似处于阻塞状态:

Auto margins on flex items have an effect very similar to auto margins in block flow:

在计算弹性基数和弹性长度时,自动页边距被视为0.

During calculations of flex bases and flexible lengths, auto margins are treated as 0.

在通过对齐内容和align-self进行对齐之前,任何肯定的可用空间在该维度上分配给自动页边距.

Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

溢出框会忽略其自动边距并最终溢出方向

Overflowing boxes ignore their auto margins and overflow in the end direction

.div-block-container { width: 2%; height: 300px; background: red; display:flex; } .div-block-vertical-line { display: block; width: 2px; height: 90%; margin-right: auto; margin-left: auto; margin-top: auto; margin-bottom: auto; background: blue; }

<div class="div-block-container"> <div class="div-block-vertical-line"></div> </div>

因此,为什么没有特殊原因.像这样简单地定义它,后来在引入flexbox时对其进行了增强.

So there is no particular reason for the why. It was simply defined like that and later enhanced when flexbox was introduced.

更多推荐

为什么margin自动适用于左/右,而不适用于顶部/底部?

本文发布于:2023-08-02 03:50:14,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1274378.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:适用于   而不   margin

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!