CSS:不能居中一个div

标签 css

我的标记页面包含如下 2 个元素:

html {
    width: 100%;
    height: 100%;
}
Body {
    height: 100%;
    width: 100%;
}
div#bg {
    height:320px;
    width:850px;
    margin: auto;
    background-color: blue;
}
#black {
    position: absolute;
    background-color: black;
    width:33%;
    height:13%;
    margin:90px auto 0;
}

...

<ul id="black"></ul>
<div id="bg"></div>

JSFiddle

我想将 black 放在 bg 中,居中位置低于其上边距 13%。不幸的是,我不能让 black 居中!我得到的是: enter image description here

谁能告诉我如何使 black 居中,使 bg 保持原位? 谢谢

最佳答案

当您尝试将绝对定位元素居中时,这个技巧就可以发挥作用。

left: 50%;
top: 50%
margin-top:-(half of the height);
margin-left: -(half of the width);

CSS

#black 
{
 position: absolute;
 background-color: black;
 width:33%;
 height:13%;
 margin-top:-7%;
 margin-left:-17%;
 left:50%;
 top:50%;
}

Js Fiddle Demo

关于CSS:不能居中一个div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21795915/

相关文章:

html - 在页面顶部设置图像

html - 难以移动导航项和下拉菜单

html - Twitter-bootstrap row-fluid up to span12 only

html - CSS 内容添加 HTML 标签

html - 点击展开 View

javascript - 在 jQuery 对象上调用 javascript 函数

html - 具有嵌套 div 的 Div 大小非常灵活

html - 停止文本在 anchor 内的图标下换行

javascript - 如何成功显示和隐藏一段文字?

html - 列图像悬停文本