html - 为什么 div 内的 div 不能很好地定位

标签 html css

<div id="progressbarr">当我使用 margin-top :50% 并期望它水平放置在中间时,仍然没有很好地包裹在它的祖先 div 中。

HTML 盒子

CSS

#col3wrap{
    height: 50px;
    background: #DDD;
}

.profilepic {
    width: 50px;
    height: 50px;
    background: red;
    float: left;
    margin: 0 10px 0 0;
}

#progressbarr {
    float: left;
    width: 300px;
    height: 20px;
    background: #eee;
    margin: 50% 0 0 0;
}

#progressbarr > div {
    background-color: green;
    width: 40%;
    height: 20px;
}

http://jsfiddle.net/Xdwhk/

最佳答案

您的边距值是使用父元素宽度计算的。为什么?好问题。我不知道,但这里有一些关于这个话题的讨论: Why are margin/padding percentages in CSS always calculated against width?

这是带有宽度设置的 #col3wrap 的演示: http://jsfiddle.net/Xdwhk/1/

尝试调整宽度以查看 margin-top 值如何随之变化。

因此,除了使用 margin-top 之外,您将不得不找到一种不同的方法来使进度条垂直居中。

这是一种方法,使用 position: relativecalc设置 top 值:

CSS

#col3wrap{
    height: 50px;
    background: #DDD;
    position: relative;
}

.profilepic {
    width: 50px;
    height: 50px;
    background: red;
    float: left;
    margin: 0 10px 0 0;
}

#progressbarr {
    float: left;
    width: 300px;
    height: 20px;
    background: #eee;
    position: relative;
    top: 30%;
    top: -webkit-calc(50% - 10px);
    top: calc(50% - 10px);
}

#progressbarr > div {
    background-color: green;
    width: 40%;
    height: 20px;
}

Demo

备注calc并非所有浏览器都支持,因此我们必须退后一步。

关于html - 为什么 div 内的 div 不能很好地定位,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19017751/

相关文章:

java - 传递 HTML 代码作为输入

javascript - 如何在点击时停止旋转画廊

javascript - 动画形式,如何检查页面刷新时的输入值?

html - 如何覆盖被其他类/元素深度嵌套的元素样式?

html - 如何设置 Angular 6 Material sidenav 从屏幕右侧从右向左打开

javascript - 调整 margin-top/bottom 与屏幕高度成比例

javascript - 无效标记重复属性

javascript - 当我自动完成输入字段时,值被标签覆盖并且在加载时也没有获得长度

html - Blogger Soho 主题标题图片未覆盖整个标题宽度和高度

c# - 在 outlook 中附加一个 html 页面作为 c# 应用程序中的 word 文档