joh*_*les 4 html css positioning
我正在尝试理解 css,所以我尽我最大的努力使下面的实验代码尽可能通用。
我有一个简单的页面,有两个框,我希望其中一个框以某种方式定位,根据为什么设置 `right` CSS 属性将元素推向左侧?需要我像这样设置它的位置position:absolute但是,我现在想添加一些低于我的绝对 div 的 div,此外我希望父 div 扩展以适应子 div 的大小。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<style type="text/css">
#outer {
position : relative;
background-color : green;
width : 500px;
height : 500px;
/* overflow : hidden; */
/* I know from working with floating elements inside divs that this works
* to cause parent divs to exand out around floating children, but this
* does not do the same thing here, it lops off the bottom of the child divs
* if I un-comment the preceding line!
*/
}
#inner {
position : absolute;
background-color : blue;
height : 400px;
width : 400px;
top : 10px;
right : 20px;
}
#top_object {
position : absolute;
top : 450px;
}
.object {
position : relative;
width : 450px;
height : 200px;
background-color : yellow;
margin-bottom : 25px;
}
/* The followsing was suggested by:
/sf/ask/119660971/
But has no effect!
*/
.clear {
clear : both;
}
</style>
</head>
<body>
<div id="outer">
<div id="inner">
</div>
<div id="top_object" class="object">
Top Object
</div>
<div class="object">
Second Object
</div>
<div class="clear"></div>
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我想让我的第一个 div 与 class object 和 id top_object 位于与顶部绝对距离的位置,就像它看起来一样。但是,我希望更多的对象 div 在顶部对象下方流动。换句话说,我想使用 top_object 为第一个带有类对象的 div 实例定义一个绝对位置,然后让以下带有类对象的 div 自然地沿着页面向下流动,在margin:25px;of 中设置 25px 边距,在.objecttop_object 之后没有需要分别设置每个对象的top:XXXpx;属性。
我的第一个问题是为什么我的第二个对象出现在我的第一个对象上方,以及如何使relative定位的对象在定位的对象下方流动absolute?
其次,当不使用浮动 div 时,如何让背景 div 展开并围绕子 div?
此外,我正在努力了解正在发生的事情,尽管对我的问题的直接回答将不胜感激,但我想听听解释为什么我所做的事情是错误的,以及为什么任何解决方案都能解决这个问题。我想了解 css 背后的逻辑,而不是看到解决问题的特定代码片段,尽管这也很好!
position: absolute;将该对象完全从文档流中移除。所以它会准确地出现在你告诉它与你的top: 450px和right或left选择器一起出现的地方。该定位不会影响您页面的任何其他元素(除非您掩盖了另一个肯定会在没有 的情况下发生的对象z-index)如果您希望所有内容都放在下方,#top_object那么您需要提供它display: block;以及您需要的任何边距。
此外,overflow: hidden将切断定义的宽度或高度之外的任何内容,因此您需要定义 min-width 和 min-height ,然后使用 overflow: auto 而不是 hidden。