在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 04:15:41  来源:igfitidea点击:

Position one element relative to another in CSS

csscss-position

提问by babak6

I want to position four divs relative to another. I have a rectangle div, and I want to insert 4 divs 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 divs 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",但这是相对于该元素的正常位置。我想定位我的divs 不是相对于它们的正常位置,而是相对于另一个元素(矩形)。我该怎么办?

采纳答案by Blender

position: absolutewill 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: absoluteon 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>

http://jsfiddle.net/wUrdM/

http://jsfiddle.net/wUrdM/