垂直定位元素的一个常见技巧是使用以下CSS:
.item {
position:absolute;
top:50%;
margin-top:-8px; /* half of height */
height: 16px;
}当在公制视图中看到Chrome时,这是您看到的:

然而,当你将鼠标悬停在元素上时,并没有显示出可视的边距,即边距位于边界之外,并且可以可视化。但负的利润率不会出现。它们看起来怎么样?是什么让它与众不同?
为什么margin-top:-8px不同于margin-bottom:8px
那么,负边际是如何工作的,它们背后的直觉是什么。他们如何“提升”一个项目(在margin-top < 0的情况下)?
发布于 2012-07-16 06:09:19
我会试着用视觉来解释它:
/**
* explaining margins
*/
body {
padding: 3em 15%
}
.parent {
width: 50%;
width: 400px;
height: 400px;
position: relative;
background: lemonchiffon;
}
.parent:before,
.parent:after {
position: absolute;
content: "";
}
.parent:before {
top: 0;
bottom: 0;
left: 50%;
border-left: dashed 1px #ccc;
}
.parent:after {
left: 0;
right: 0;
top: 50%;
border-top: dashed 1px #ccc;
}
.child {
width: 200px;
height: 200px;
background: rgba(200, 198, 133, .5);
}
ul {
padding: 5% 20px;
}
.set1 .child {
margin: 0;
position: relative;
}
.set2 .child {
margin-left: 75px;
position: relative;
}
.set3 .child {
margin-left: -75px;
position: relative;
}
/* position absolute */
.set4 .child {
top: 50%;
left: 50%;
margin: 0;
position: absolute;
}
.set5 .child {
top: 50%;
left: 50%;
margin-left: 75px;
position: absolute;
}
.set6 .child {
top: 50%; /* level from which margin-top starts
- downwards, in the case of a positive margin
- upwards, in the case of a negative margin
*/
left: 50%; /* level from which margin-left starts
- towards right, in the case of a positive margin
- towards left, in the case of a negative margin
*/
margin: -75px;
position: absolute;
}<!-- content to be placed inside <body>…</body> -->
<h2><code>position: relative;</code></h2>
<h3>Set 1</h3>
<div class="parent set 1">
<div class="child">
<pre>
.set1 .child {
margin: 0;
position: relative;
}
</pre>
</div>
</div>
<h3>Set 2</h3>
<div class="parent set2">
<div class="child">
<pre>
.set2 .child {
margin-left: 75px;
position: relative;
}
</pre>
</div>
</div>
<h3>Set 3</h3>
<div class="parent set3">
<div class="child">
<pre>
.set3 .child {
margin-left: -75px;
position: relative;
}
</pre>
</div>
</div>
<h2><code>position: absolute;</code></h2>
<h3>Set 4</h3>
<div class="parent set4">
<div class="child">
<pre>
.set4 .child {
top: 50%;
left: 50%;
margin: 0;
position: absolute;
}
</pre>
</div>
</div>
<h3>Set 5</h3>
<div class="parent set5">
<div class="child">
<pre>
.set5 .child {
top: 50%;
left: 50%;
margin-left: 75px;
position: absolute;
}
</pre>
</div>
</div>
<h3>Set 6</h3>
<div class="parent set6">
<div class="child">
<pre>
.set6 .child {
top: 50%;
left: 50%;
margin: -75px;
position: absolute;
}
</pre>
</div>
</div>
发布于 2012-07-16 04:12:10
边距是元素外部的间距,就像填充是元素内部的间距一样。
设置底边距可指示当前块下方的距离。设置负上边距表示您希望块上方的间距为负值。负间距本身可能是一个令人困惑的概念,但就像正上边距将内容向下推的方式一样,负上边距也会拉高内容。
发布于 2012-07-16 04:09:26
-8px的边距顶部意味着它将比没有边际的情况高出8px。
下边距为8px意味着,如果下边距为0,则下边距将进一步降低8px。
https://stackoverflow.com/questions/11495200
复制相似问题