如何根据CSS的第一个div设置第二个div的左侧和顶部

时间:2015-12-23 17:11:10

标签: html css

我可以一个接一个地定位两个div。

#wrapper {
  margin-left: auto;
  margin-right: auto;
  height: auto;
  width: auto;
}
#inner1 {
  float: left;
  width: 200px;
  height: 200px;
  background-color: red;
}
#inner2 {
  width: 200px;
  height: 200px;
  float: left;
  clear: left;
  background-color: green;
}
<div id="wrapper">
  <div id="inner1">First One</div>
  <div id="inner2">Second One</div>
</div>

但我不能做的事情是根据第一个div设置第二个div和top。

我希望set 2nd div top = 1st div height + 20 px by CSS不是通过JavaScript

我希望set 2nd div left = 1st div left by CSS不是通过JavaScript

是否可以通过css才能在旧浏览器中运行。

如果可能,

与示例代码讨论。感谢

2 个答案:

答案 0 :(得分:0)

您无法仅使用css引用其他元素计算样式!

但是

有很多技巧可以完成你正在寻找的仅使用css的行为

示例1 - using the margin property

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
}
#inner1{
  float:left; 
  width:200px;
  height:200px;
  background-color:red;
}
#inner2{
  margin-top:-200px; //we decrease the the top margin with the height of the pervius element
  width:200px;
  height:200px;
  float:left; 
  clear: left;
  background-color:green;
} 

示例2 - using the position property

#wrapper{
    margin-left:auto;
    margin-right:auto;
    height:auto; 
    width:auto;
    position:relative; //makeing the wrapper "relative"
}

#inner1{
  position:absolute; // setting position absolute
  top:0;             // and top 0 so they have the same top
  float:left; 
  width:200px;
  height:200px;
  background-color:red;
}
#inner2{
  position:absolute; // setting position absolute
  top:0;             // and top 0 so they have the same top
  width:200px;
  height:200px;
  float:left; 
  clear: left;
  background-color:green;
} 

答案 1 :(得分:0)

为什么不在第二个div使用margin-top?

#inner2{
   margin-top: 20px;
}

你不能再使用浮动了。