这是图表的 html。我希望第二个(中间)div 从第一个(顶部)div 结束的地方开始(即在其 75px 宽度的右端),所以在下面的样式中,我将 margin-left
设置为中间的 div 为 75px。继续这种模式,我希望第三个(底部)div 从中间 div 结束的地方开始。由于顶部和中间 div 的宽度为 120px,我将底部 div 的 margin-left:
设置为 120px
。从this jsfiddle可以看出, 三个 div 都从左边缘开始,而不是缩进所需的像素数。
这种我笨拙的方法搞不定的效果,正确的做法是什么? (注意,div 应该保持在不同的行上,而不是合并成一行)
HTML
<div class="another_chart">Blah blah graph
<div class="another_blue" style="width: 75px;">25</div>
<div class="another_pink" style="width: 45px;">15</div>
<div class="another_yellow" style="width: 60px;">20</div>
</div>
CSS
.another_chart div {
text-align:right;
padding:3px;
margin:1px;
color:#000;
width:600px
}
.another_blue {
font:15px sans-serif;
background-color:#4682b4;
text-align:right;
padding:3px;
margin:1px;
color:#fff;
height:20px;
line-height:20px
}
.another_pink {
font:15px sans-serif;
background-color:#f5c5f2;
text-align:right;
padding:3px;
margin-left:75px;//the middle div should start 75px from the left color
height:20px;
line-height:20px
}
.another_yellow {
font:15px sans-serif;
background-color:#ebfa02;
text-align:right;
padding:3px;
margin-left:120px;//the bottom div should start 120px from the left
color
height:20px;
line-height:20px
}
最佳答案
向左浮动并应用上边距。
CSS
.another_chart div {
float: left;
}
HTML
<div class="another_chart">
<div class="another_blue" style="width: 75px;">25</div>
<div class="another_pink" style="width: 45px; margin-top: 2em;">15</div>
<div class="another_yellow" style="width: 60px; margin-top: 4em;">20</div>
</div>
您还可以删除一些多余的 CSS 样式:
.another_chart div {
text-align: right;
font: 15px sans-serif;
padding: 3px;
color: #000;
width: 600px;
float: left;
height: 20px;
}
.another_blue {
background-color: steelblue;
}
.another_pink {
background-color: #f5c5f2;
}
.another_yellow {
background-color: #ebfa02;
}
关于html - 相对于彼此定位嵌套的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24792979/