标签水平居中方法

122 阅读1分钟

如果要让 div、p 等大盒子水平居中,直接给当前元素本身设置margin : 0 auto ;即可实现。

margin : 0 auto ;一般针对有固定宽度的盒子,如果大盒子没有设置宽度,则会默认占满父元素的宽度

1. 大盒子有固定宽度

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .one {
        width: 100px;
        height: 100px;
        margin: 0 auto;
        background-color: skyblue;
      }
    </style>
  </head>
  <body>
    <div class="one">123456789</div>
  </body>
</html>

image.png

2. 大盒子没有设置宽度

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .one {
        width: 150px;
        height: 100px;
        background-color: skyblue;
      }
      .two {
        margin: 0 auto;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div class="one">
      <div class="two">123456789</div>
    </div>
  </body>
</html>

image.png

3. 大盒子、元素同时水平居中

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .one {
        width: 300px;
        height: 300px;
        background-color: skyblue;
      }
      .two {
        width: 100px;
        height: 100px;
        margin: 0 auto;
        text-align: center;
        background-color: pink;
      }
    </style>
  </head>
  <body>
    <div class="one">
      <div class="two">123456789</div>
    </div>
  </body>
</html>

image.png