我想要实现的是将字符串居中,同时将其强制到容器div的底部,但以下内容在不同的浏览器中会产生3种不同的结果。
<style>
#outer {
position: relative;
background-color:blue;
height: 50px;
text-align: center;
}
#inner {
bottom: 0px;
position: absolute;
background-color:red;
}
</style>
</head>
<body>
<div id="outer">
<span id="inner">
aaaaaaaaaaaaaaaaaaaaaaa
</span>
</div>
</body>
Chrome 完美地将 #inner 居中。Firefox 开始从完美的中心向右输出字符串,因此不知何故它看起来有点移动,字符串越长,眼睛越明显。IE 从左侧开始输出文本。
有什么解决方法吗?哪些行为符合标准?
我认为你应该给左和右:0在你的 CSS 中是这样的
#inner {
position: absolute;
bottom: 0;
left: 0;
right: 0;
background-color: red;
}
将text-align: center;
放在div#inner 上,然后将其从div#outer 中删除。
您的内部应该有一个负边距,是元素宽度的 1/2。
#inner{
position:absolute;
left:50%;
width:500px;
margin-left:-250px;
}
在其上声明宽度时,才有可能将内部元素垂直居中定位与绝对定位相结合,这只有在它是非内联元素时才有效。
所以你需要这个额外的规则:
#inner{
display:inline-block;
width:<yourWidth>px;
margin-left:-<yourWidth/2>px;
left:50%;
}
或者,您可以执行以下操作:
#inner{
display:block;
left:0;
text-align:center;
}
旁注:根据规范 0 可能永远不会有单位,所以总是写top:0;
而不是top:0px;
好吧,如果CSS变得古怪,你可以使用jQuery。首先使用 CSS 隐藏内容,然后让 jQuery 居中并在加载内容时取消隐藏它。这样的事情应该有效:
$(document).ready(function() {
var newWidth = ($('#outer').width() - $('#inner').width()) / 2;
$('#inner').css({'visibility': 'visible', 'margin-left': newWidth});
});
这是未经测试的,但应该适用于任何条件。