html - 相对于彼此定位嵌套的div

标签 html css

这是图表的 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
}

最佳答案

向左浮动并应用上边距。

Have a fiddle!

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

Cleaner fiddle!

.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/

相关文章:

php - 使用 PHP 减少 HTML 输出中的间距

css - 修复我网站上 div 之间的奇怪间距

html - 保持容器固定并在窗口调整大小时显示水平滚动条

php - 我从哪里开始更改主页?

javascript - 循环 2 "Loading"背景图片

Javascript isNaN() 函数被忽略

html - 使用 css3 样式化 svg 元素

javascript - 使用 CSS 和 JavaScript 旋转盒子

html - 如何编写其中包含复杂内容的链接,使其有效且正确

css - 将 html div 居中