#parent{border:1px, solid, black; background:#efefef; height:100px;}/*To indicate the parent*/
#child1{background:green;position:relative;width:60%;height:30px; left:5%;top:10px;}
#child2{background:rgb(9,9,9);position:relative;width:30%;height:50px;color:white;left:65%;top:10px;}
<div id = "parent">
<div id = "child1">This is child one</div>
<div id = "child2">This is child two</div>
</div>
我希望这两个元素在不使用position绝对位置的情况下是相同的顶部,因为第二个元素高度会动态变化并影响它下面的另一个元素。
答案 0 :(得分:0)
您可以使用display: inline-block;
,如下所示:
#parent {
border: 1px solid black;
background: #efefef;
height: 100px;
} /*To indicate the parent*/
#child1 {
background: green;
position: relative;
width: 60%;
height: 30px;
top: 10px;
}
#child2 {
background: rgb(9,9,9);
position: relative;
width: 30%;
height: 50px;
color: white;
top: 10px;
}
.aligned {
display: inline-block;
}
&#13;
<div id = "parent">
<div id = "child1" class="aligned">This is child one</div>
<div id = "child2" class="aligned">This is child two</div>
</div>
&#13;
@Sujata Chanda提到
或 float: left;
,见下文:
#parent {
border: 1px solid black;
background: #efefef;
height: 100px;
} /*To indicate the parent*/
#child1 {
background: green;
position: relative;
width: 60%;
height: 30px;
top: 10px;
}
#child2 {
background: rgb(9,9,9);
position: relative;
width: 30%;
height: 50px;
color: white;
top: 10px;
}
.aligned {
float: left;
}
&#13;
<div id = "parent">
<div id = "child1" class="aligned">This is child one</div>
<div id = "child2" class="aligned">This is child two</div>
</div>
&#13;
注意:我刚刚将left
属性移除到您的CSS,因为元素将被对齐,所以不再需要它。如果你想在两者之间留出一些空间,我建议你使用margin
属性。
答案 1 :(得分:0)
#parent{border:1px, solid, black; background:#efefef; height:100px;}/*To indicate the parent*/
#child1{background:green;position:relative;width:60%;height:30px; left:5%;top:10px;float: left;}
#child2{background:rgb(9,9,9);position:relative;width:30%;height:50px;color:white;left:65%;top:10px;}
<div id = "parent">
<div id = "child1">This is child one</div>
<div id = "child2">This is child two</div>
</div>
答案 2 :(得分:0)
将float:left;
添加到divs
。
从第二个left:65%;
移除div
。
#parent{border:1px, solid, black; background:#efefef; height:100px;}/*To indicate the parent*/
#child1{background:green;position:relative;width:60%;height:30px; left:5%;top:10px;float:left;}
#child2{background:rgb(9,9,9);position:relative;width:30%;height:50px;color:white;top:10px;float:left;}
&#13;
<div id = "parent">
<div id = "child1">This is child one</div>
<div id = "child2">This is child two</div>
</div>
&#13;