CSS相对于HTML页面上的特定元素的定位

时间:2014-11-15 07:09:09

标签: html css

在CSS中定位是最有趣的主题之一,所以在绝对和相对定位中我们相对于页面的位置,任何人都可以解释我如何相对于同一页面上的另一个元素定位元素,例如我有html页面就像。

<!DOCTYPE html>
<html>
<head>
 <style>
 .block{
  display:block;
 }

</head>
<body>
<div class="container1 block"> content</div>
content here.....//can be img a or whatever html tag.
<div class="randomContainers"> <div class="container2 block"> </div></div>
</body>
</html>

所以在上面的代码中,我如何相对于div.container2定位div.container1?

1 个答案:

答案 0 :(得分:2)

演示 - http://jsfiddle.net/victor_007/4yzLo9ev/

您需要将父级设置为父级position:relative元素的position:absolute

&#13;
&#13;
.relative {
  position: Relative;
  width: 400px;
  border: 1px solid red;
  height: 200px;
}
.absolute {
  position: absolute;
  width: 150px;
  height: 150px;
  bottom: -75px;
  left: 25px;
  border: 1px solid blue;
  background: url(http://placeimg.com/150/150/any);
}
&#13;
<div class="relative">
  <div class="absolute"></div>
</div>
&#13;
&#13;
&#13;

  

具有 position:absolute 的元素将根据   在其顶部&#39;中指定的坐标并且&#39;离开&#39;属性,相对于   最近的祖先。或者它将根据窗口

进行定位

如下图所示,您可以看到body height green-border

Fiddle

  

如果你想根据定位绝对div   身体,身体应相对定位

Fiddle

  

如果父级和祖父级都是相对的,则div将对齐   最近的父母

Fiddle