使用绝对定位设置margin: 0 auto失去水平居中效果解决方法


1、解决方法代码

DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>解决绝对定位margin水平居中效果title>
    <style>
        .one{
            width: 200px;
            height: 200px;
            background-color: red;
            position: relative;
        }

        .two{
            width: 100px;
            height: 100px;
            background-color: green;
            margin: 0 auto;
            position: absolute;
            right: 0;
            left: 0;
        }

    style>
head>
<body>
<div class="one">
    <div class="two">div>
div>
body>
html>

注:div class类名添加了绝对定位position: absolute;后margin: 0 auto;会失去水平居中设置。解决这个问题需要对绝对定位设置right: 0;和left: 0; 这两个。这样即使使用了绝对定位也会使水平居中生效