Html 使相对定位的元素不影响布局/高度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30580999/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make relatively positioned element not affect layout/height
提问by Christian Stewart
I've got an icon, like this:
我有一个图标,像这样:
<div class="mydiv">
<i style="position: relative; top: 3px;"></i>
</div>
I want to move the icon down by 3 pixels, which works. But the div still has a greater height to it because the icon is technically expanding the height of the line. How do I make the icon not affect the layout at all, and not make the div bigger in height?
我想将图标向下移动 3 个像素,这是可行的。但是 div 仍然具有更大的高度,因为图标在技术上扩展了线条的高度。如何使图标完全不影响布局,并且不使 div 的高度变大?
回答by
http://www.w3.org/TR/css3-positioning/#rel-pos
6.1. Relative positioning
A relatively positioned box keeps its normal flow size, including line breaks and the space originally reserved for it.
http://www.w3.org/TR/css3-positioning/#rel-pos
6.1. 相对定位
相对定位的框保持其正常的流大小,包括换行符和最初为其保留的空间。
Basically a relatively positioned element still affects the surrounding elements. You're looking for position: absolute
, but heres a trick from the same document
基本上一个相对定位的元素仍然会影响周围的元素。您正在寻找position: absolute
,但这是同一文档中的一个技巧
...
A relatively positioned box establishes a new containing blockfor absolutely positioned descendants. (This is a common use of relatively positioned boxes.) The section on containing blocks explains when a relatively positioned box establishes a new containing block.
...
一个相对定位的盒子为绝对定位的后代建立一个新的包含块。(这是相对定位框的常见用法。)包含块的部分解释了相对定位框何时建立新的包含块。
So by setting the parent to position: relative
you turn it into a containing block, which means that absolutely positioned elements contained within will be positioned relative to the edges of the parent rather than the root containing block (the window).
因此,通过将 parent 设置为position: relative
您将其转换为包含块,这意味着其中包含的绝对定位元素将相对于父元素的边缘而不是根包含块(窗口)定位。
Hello World.
<span style="position: relative; background-color: red;">
This will be shown inline
<span style="position: absolute; top: 100%; left: 0px;">
This will be below
</span>
</span>
回答by wjkawecki
You should make the parent's position relative and the actual element absolute.
您应该使父元素的位置相对而实际元素是绝对的。
<div class="mydiv">
<i style="position: absolute; top: 3px;"></i>
</div>
.mydiv {
position: relative;
}
回答by Tom Leppens
why not fix it with negative margin?
为什么不用负边距修复它?
<div class="mydiv">
<i style="position: relative; top: 3px; margin-bottom:-3px;"></i>
</div>