Html 如何将一个div放在另一个div下面?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19338323/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 14:24:16  来源:igfitidea点击:

How to place a div below another div?

htmlcss

提问by rram

I have a #sliderdiv with an image. After that, I have a #contentdiv which has text. I have tried position:relativeso I think it should come after the previous div, I mean #sliderbut here it is not coming that way.

我有一个#slider带有图像的div。在那之后,我有一个#content带有文本的div。我已经尝试过,position:relative所以我认为它应该在上一个 div 之后出现,我的意思是#slider但在这里它不是那样的。

What is the problem here? How to overcome it?

这里有什么问题?如何克服它?

HTML

HTML

<div id="slider">
    <img src="http://oi43.tinypic.com/25k319l.jpg"/>
</div>
<div id="content">
    <div id="text">
        sample text
    </div>
</div>

CSS

CSS

#slider {
    position:absolute;
    left:0;
    height:400px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

JSFIDDLE

JSFIDDLE

采纳答案by Alain1405

You have set #slideras absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #contentdiv is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

您已设置#sliderabsolute,这意味着它“相对于最近的定位祖先定位”(令人困惑,对吧?)。同时,#contentdiv 是相对放置的,意思是“相对于它的正常位置”。所以2个div的位置是不相关的。

You can read about CSS positioning here

您可以在此处阅读有关 CSS 定位的信息

If you set both to relative, the divs will be one after the other, as shown here:

如果您将两者都设置为relative,则 div 将一个接一个,如下所示:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

http://jsfiddle.net/uorgj4e1/

回答by Jonathan Marzullo

what about changing the position: relativeon your #content #textdiv to position: absolute

如何改变位置:相对于你的#content #textdiv 到位置:绝对

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

http://jsfiddle.net/CaZY7/12/

then you can use the css properties leftand topto position within the #content div

然后你可以使用 css 属性lefttop在 #content div 中定位