方法一(推荐)、是将 potition:absolute 元素的 left 和 right 同时设置为 0,并且设置 margin:0 auto 。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>www.02405.com</title>
</head>
<style>
    #root{
        width: 100%;
        height: 100px;
        position: relative;
        background: #eee;
    }
    .block{
        height: 40px;
        width: 200px;
        position: absolute;
        left: 0;
        right:0;
        margin: 0 auto;
        background: #555;
    }
</style>
<body>
    <div id="root">
        <div class="block">www.02405.com</div>
    </div>
</body>
</html>

方法二、将 potition:absolute 元素 的 left 设置为 50%,margin-left 设置为负的父元素的宽度的一半,也就是 -width/2 ,这个的缺点是要知道父元素的确切宽度。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>www.02405.com</title>
</head>
<style>
    #root{
        width: 960px;
        height: 100px;
        position: relative;
        background: #eee;
    }
    .block{
        height: 40px;
        width: 200px;
        position: absolute;
        left: 50%;
        margin-left: -480px;
        background: #555;
    }
</style>
<body>
    <div id="root">
        <div class="block">www.02405.com</div>
    </div>
</body>
</html>

方法三、在 potition:absolute 元素外部套一层 div,对这个 div 设置绝对定位,然后再设置里面的元素 margin:0 auto。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>www.02405.com</title>
</head>
<style>
    #root{
        width: 100%;
        height: 100px;
        position: relative;
    }
    .container{
        width: 100%;
        height: auto;
        position: absolute;
        left: 0;
        top: 40px;
    }
    .block{
        height: 20px;
        width: 30px;
        position: relative;
        margin: 0 auto;
    }
</style>
<body>
    <div id="root">
        <div class="container">
            <div class="block">www.02405.com</div>
        </div>
    </div>
</body>
</html>

 

(adsbygoogle = window.adsbygoogle || []).push({});