绝对定位元素text-align:center下的居中对齐实例页面

展示

回到相关文章 »

代码

CSS代码:
.test_box{width:60%; height:381px; margin:1em auto; text-align:center; background-color:#f0f3f9;}
.test_image{position:absolute; margin-left:-256px;}
            
HTML代码:
<div id="testBox" class="test_box">
    <img class="test_image" src="//image.zhangxinxu.com/image/study/s/s512/mm1.jpg" height="381" />
</div>
<div class="test_button"><button id="testButton">添加&nbsp;空格修复IE8+,Chrome等浏览器居中显示</button></div>  
            
JS代码:
var $ = function(id){
    return document.getElementById(id);
};
$("testButton").onclick = function() {
    var eleBox = $("testBox"), htmlBox = eleBox && eleBox.innerHTML.replace(/^\s+/, "");
    if (/^<img/i.test(htmlBox)) {
        eleBox.innerHTML = "&nbsp;" + htmlBox;
        this.innerHTML = "已修复";
    }
};