CSS绝对定位与相对定位一起使用时,"top"属性不起作用。

13

我正在处理一个使用相对定位的div来包含绝对定位的div的网站。我相信我理解了这个概念,一切都运行得很好,但是我似乎无法使top属性起作用。left可以工作,但是top不能。我的代码如下:

<div id="imagemenu">
    <div class="west">
        <img src="/makingmusicstore/wp-content/themes/makingmusic/img/west.png" alt="west">
    </div>
    <div class="southwest">
        <img src="/makingmusicstore/wp-content/themes/makingmusic/img/southwest.png alt=" southwest ">
    </div>
    <div class="south ">
        <img src="/makingmusicstore/wp-content/themes/makingmusic/img/south.png " alt="south ">
    </div>
    <div class="logo ">
        <img src="/makingmusicstore/wp-content/themes/makingmusic/img/logo.png " alt="Making Music Store ">
    </div>
</div>

CSS

#imagemenu {
    position: relative;
}
.logo img {
    position: absolute;
    width: 20%;
    top: 50%;
    left: 40%;
}
.west img {
    position: absolute;
    width: 30%;
    left: 15%;
}
.southwest img {
    position: absolute;
    width: 30%;
    left: 15%;
}
.south img {
    position: absolute;
    left: 35%;
}

网站是adams-web.net/makingmusicstore,目前还很混乱,直到我解决顶部属性问题。按照我的理解,标志应该在页面下方更远处,但它并没有像我想象中的那样工作。我不确定我漏掉了什么。当我将位置更改为静态时,它确实有效,但无法保持正确的位置。


你从来没有把网站弄好吗?我去看了一下想看看你做了什么,但是。你是把它拆掉了还是没能让它工作? - TheArchitecta
2个回答

25

定义您的父 div 高度,然后在顶部使用 top % 作为绝对定位的 div

就像这样:

.parent {
    position: relative;
    height: 100px;
}
.child {
    position: absolute;
    top: 50%;
}

如果您没有定义父级 div 的高度,则使用 top 中的 px 值

.child {
    top: 100px;
}

1
当然!谢谢您的回复,我花了很长时间来研究这个问题,结果答案是如此简单。 - Rob Adams

6

#imagemenu 添加 widthheight

例如:

#imagemenu {
    width: 100%;
    height: 400px;
}

然后再次检查position: absolute是否起作用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接