小编典典

绝对定位里面相对定位?

css

根据W3Schools:

相对定位的元素通常用作绝对定位元素的容器块。

为什么是这样?有没有很好的例子?


阅读 441

收藏
2020-05-16

共1个答案

小编典典

一个很好的例子是当您想将某些内容放置到页面上或相对于容器/ div放置时。

这向您显示,如果绝对div不在“相对” div内,则内容将与文档主体对齐。

请注意,绿色div(#box1position: relative的div内部(#inner1)的对齐方式为的上/右对齐#box1

蓝色框(#box2)具有与绿色框(#box1)完全相同的HTML布局,但不包含position: relative且注意其中的div(#inner2)对齐到顶部的右/右body

#box1, #box2 {
    width: 100px;
    height: 100px;
    color: white;
    text-align: center;
    line-height: 100px;
}
#box1 {
    background: green;
    position: relative;
}
#box2 {
    background: blue;
}

#inner1, #inner2 {
    width: 50px;
    height: 50px;
    top: 0;
    right: 0;
    position: absolute;
    background: black;
    opacity: 0.5;
    color: white;
    text-align: center;
    line-height: 50px;
}

这是克里斯·科耶尔(Chris Coyier)撰写的一篇不错的文章。

具有相对位置的页面元素使您可以控制在其中绝对放置子元素的位置。

2020-05-16