在 CSS 中相对于另一个元素定位一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11151089/
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
Position one element relative to another in CSS
提问by babak6
I want to position four div
s relative to another. I have a rectangle div
, and I want to insert 4 div
s at its corners. I know that CSS has an attribute "position:relative"
, but this is relative to the normal position of that element. I want to position my div
s not relative to their normal position, but relative to another element (the rectangle). What should I do?
我想div
相对于另一个定位四个。我有一个矩形div
,我想div
在它的角上插入 4 s。我知道 CSS 有一个属性"position:relative"
,但这是相对于该元素的正常位置。我想定位我的div
s 不是相对于它们的正常位置,而是相对于另一个元素(矩形)。我该怎么办?
采纳答案by Blender
position: absolute
will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static
.
position: absolute
将通过坐标定位元素,相对于最近定位的祖先,即最近的父元素不是position: static
。
Have your four divs nested inside the target div, give the target div position: relative
, and use position: absolute
on the others.
将您的四个 div 嵌套在目标 div 中,给出目标 div position: relative
,然后position: absolute
在其他div 上使用。
Structure your HTML similar to this:
像这样构建您的 HTML:
<div id="container">
<div class="top left"></div>
<div class="top right"></div>
<div class="bottom left"></div>
<div class="bottom right"></div>
</div>
And this CSS should work:
这个 CSS 应该可以工作:
#container {
position: relative;
}
#container > * {
position: absolute;
}
.left {
left: 0;
}
.right {
right: 0;
}
.top {
top: 0;
}
.bottom {
bottom: 0;
}
...
回答by Aaron Miler
I would suggest using absolute positioning within the element.
我建议在元素内使用绝对定位。
I've created this to help you visualize it a bit.
我创建了这个来帮助你想象一下。
#parent {
width:400px;
height:400px;
background-color:white;
border:2px solid blue;
position:relative;
}
#div1 {position:absolute;bottom:0;right:0;background:green;width:100px;height:100px;}
#div2 {width:100px;height:100px;position:absolute;bottom:0;left:0;background:red;}
#div3 {width:100px;height:100px;position:absolute;top:0;right:0;background:yellow;}
#div4 {width:100px;height:100px;position:absolute;top:0;left:0;background:gray;}
<div id="parent">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</div>