如何在CSS工作的负边距,为什么是(margin-top:-5!= margin-bottom:5)? [英] How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

查看:220
本文介绍了如何在CSS工作的负边距,为什么是(margin-top:-5!= margin-bottom:5)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

垂直定位元素的常见技巧是使用以下CSS:

  .item {
position:绝对;
top:50%;
margin-top:-8px; / * half of height * /
height:16px;
}

在Chrome中的指标视图中看到的是: / p>

>



但是,当您将鼠标悬停在元素上时,没有描绘视觉边缘,即边距在边框外部,并且可以可视化。但是负利润并没有出现。



为什么 margin-top:-8px margin-bottom:8px 不一样



工作和他们背后的直觉。 >

解决方案

负边距在css中有效,并且了解其(符合)行为主要基于)?我看到你正在尝试垂直居中的元素,所以为什么你必须设置 margin-top:-8px; 而不是 margin-top :-50%;



好吧,垂直居中在CSS中比它应该更难。当设置顶部底部边距(%)时,该值计算为总是相对于包含块的宽度的百分比。这是一个常见的陷阱,很少在w3 docos之外描述这个怪癖。


A common trick for vertical positioning elements is to use the following CSS:

.item {
    position:absolute;
    top:50%;
    margin-top:-8px; /* half of height */
    height: 16px;
}

When seen in the metric view as in Chrome this is what you see:

However, there is no visual margin depicted when you hover over the element i.e. the margin is 'outside' the border and can be visualized. But negative margins don't show up. How do they look and what is it that makes it different?

Why is margin-top:-8px not the same as margin-bottom:8px?

So just how do negative margins work and what's the intuition behind them. How do they 'bump up' (in case of margin-top < 0) an item?

解决方案

Negative margins are valid in css and understanding their (compliant) behaviour is mainly based on the box model and margin collapsing. While certain scenarios are more complex, a lot of common mistakes can be avoided after studying the spec.

For instance, rendering of your sample code is guided by the css spec as described in calculating heights and margins for absolutely positioned non-replaced elements.

If I were to make a graphical representation, I'd probably go with something like this (not to scale):

The margin box lost 8px on the top, however this does not affect the content & padding boxes. Because your element is absolutely positioned, moving the element 8px up does not cause any further disturbance to the layout; with static in-flow content that's not always the case.

Bonus:

Still need convincing that reading specs is the way to go (as opposed to articles like this)? I see you're trying to vertically center the element, so why do you have to set margin-top:-8px; and not margin-top:-50%;?

Well, vertical centering in CSS is harder than it should be. When setting even top or bottom margins in %, the value is calculated as a percentage always relative to the width of the containing block. This is rather a common pitfall and the quirk is rarely described outside of w3 docos

这篇关于如何在CSS工作的负边距,为什么是(margin-top:-5!= margin-bottom:5)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆