Html 为什么我元素上的静态位置不相对于父div定位?

Html 为什么我元素上的静态位置不相对于父div定位?,html,css,Html,Css,我有一个容器div,分配了位置:relative,在这个div内我有一个锚定标签,分配了位置:fixed。而不是 CSS *{padding:0;margin:0;} .main { width: 300px; position: relative; background: #eee; } p { margin-bottom: 20px; } .btn { display: block; width: 100px; height: 1

我有一个容器div,分配了
位置:relative
,在这个div内我有一个锚定标签,分配了
位置:fixed
。而不是

CSS

*{padding:0;margin:0;}

.main {
    width: 300px;
    position: relative;
    background: #eee;
}

p {
    margin-bottom: 20px;
}

.btn {
    display: block;
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    text-align: center;
    line-height: 100px;
    position: fixed;
    right: 0;
    bottom: 0;
}

固定位置元素相对于浏览器窗口定位

它将自身定位到主体,而不是相对于其父div进行定位

不是主体,而是视口–:

固定定位是绝对定位的一个子类别。唯一的区别是,对于固定定位的框,包含的块由视口建立


按设计工作。

正如其他人所说,
位置:fixed
是相对于视口的,因此单凭css无法实现所需。如果您想将
btn
固定到
main
容器,那么您还需要使用一个带有一点javascript的绝对定位

在本例中,我使用jQuery库移动按钮:


你不清楚你希望这个布局如何表现,但我敢打赌有CSS的方法来修复它。如果您希望它保持在右下角:

.btn {
    display: block;
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    text-align: center;
    line-height: 100px;
    position: fixed;
    left: 200px; 
    bottom: 0;
}
您还可以使用边距来进一步定位元素。例如,如果要使其居中,请执行以下操作:

.btn {
    display: block;
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    text-align: center;
    line-height: 100px;
    position: fixed;
    left: -50px;
    margin-left: 50%;
    bottom: 0;
}
.btn {
    display: block;
    width: 100px;
    height: 100px;
    background: red;
    color: white;
    text-align: center;
    line-height: 100px;
    position: fixed;
    left: -50px;
    margin-left: 50%;
    bottom: 0;
}