Position one element relative to another in CSS

你说的曾经没有我的故事 提交于 2019-11-29 02:48:11
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/

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<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:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!