何时准确使用相对位置 [英] When to exactly use position relative
问题描述
我不是CSS方面的专家.我没有给任何职位,并且有css之类的
I am not much expert in css. I did not give any position and have css like
#myId{
margin-left: 10px;
margin-top: 10px;
}
#myId{
position: relative;
left: 10px;
top: 10px;
}
两者都完全符合我的要求.我什么时候应该准确地使用相对位置.与其他相比有什么优势或劣势吗?
Both did exactly what i wanted. When should i use relative position exactly. Any advantage or disadvantage over other?
推荐答案
案例1
您具有位于 absolute
内的内部元素,并希望该元素坚持其父元素.比您将 position:relative
应用于父元素.默认情况下,绝对元素会从DOM流中弹出,并从最近的相对元素中占据位置(默认情况下为html)
You have inner element that is positioned absolute
and want that element to stick to it's parent. Than you apply position: relative
to parent element. By default absolute element pops out from DOM flow and takes position from closest relative element (html by default)
案例2
您想移动元素,但仍将其保留在DOM流中.比应用 position:relative
并使用 left
/ right
/ top
/ bottom
属性.
You want to move element but still keep it in DOM flow. Than apply position: relative
and move it with left
/right
/top
/bottom
properties.
案例3
您想将一个元素放置在另一个元素上.静态元素不会生效 z-index
,这就是为什么需要将其位置设置为 relative
, static
或 fixed 代码>
You want to place one element over another. Static elements does not take effect of z-index
that's why you need to set it's position to relative
, static
or fixed
可能还有其他用例
.a {
background-color: #ddd;
left: 50px;
top: 150px;
position: relative;
width: 200px;
height: 200px;
text-align: center;
}
.absolute,
.a div {
position: absolute;
left: 50px;
top: 50px;
width: 100%;
height: 60px;
background-color: rgba(250, 0, 0, .4);
}
<div class="a">
HTML > relative
<div>HTML > relative > absolute</div>
</div>
<div class="absolute">HTML > absolute</div>
.a {
position: relative;
left: -20px;
}
.b {
margin-left: -20px;
}
.wrapper {
border-bottom: 2px solid #454545;
}
<div class="wrapper">
relative moving content
<br/>
<span>some content to overlap</span>
<span class="relative a">some content</span>
<span>some content</span>
</div>
<div class="wrapper">
using margins
<br/>
<span>some content to overlap</span>
<span class="relative b">some content</span>
<span>some content</span>
</div>
这篇关于何时准确使用相对位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!