css中将div定位居中

        一直,我是认为定一个width,然后写一句margin:0 auto,就可以,但是有时也会不管用。

       例如当我要定一个宽度为700的div,用相对定位定在中间。任你怎么拉伸都是居中。而position:absolute; left:50%; margin-left:-350px; 而这个350px则是这个元素宽度的一半。

        

   看实例子

     

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<script type="text/javascript" src="jquery-2.0.3.js"></script>
<style>
.scroll{height:2000px;}
.main{100%;height:550px; background-color:#fe3a08; position:relative;}    
.cent{700px;color:#fff; font-size:46px; font-family:"幼圆"; position:absolute; left:50%; margin-left:-350px;line-height:500px;top:0px;}
</style>
<script>
function changeTop(obj, value) {
    var offsetTop = obj.offset().top + value;
    var scrollTop = $(window).scrollTop();
    console.log(offsetTop);
    console.log(scrollTop);
    var result = scrollTop - offsetTop ;
    if ((offsetTop < scrollTop) ) {
        obj.find(".bg-image").stop(true,true).animate({ "top": result }, 300);
    }
    if (offsetTop +550 < scrollTop) {
        obj.find(".bg-image").stop(true,true).animate({ "top": "0px" }, 300);
    }
}
$(function(){
    $(window).scroll(function () {
        changeTop($(".main"),80);
    })    
})

</script>
</head>

<body>
<div class="scroll">
    <div class="main">
        <div class="cent bg-image">
                R6 BRANCH OFFICE | 工程管理
        </div>
    </div>
</div>
</body>
</html>
原文地址:https://www.cnblogs.com/wanliyuan/p/3756594.html