美文网首页
CSS 水平居中

CSS 水平居中

作者: 我是Msorry | 来源:发表于2020-12-28 17:01 被阅读0次

当居中 div 宽度不固定时

1. 设置左右外边距值相等

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    .parent {
      width: 200px;
      height: 300px;
      background: #f60;
      border:7px solid black;
    }
    .child {
      outline:5px solid green;
      margin-left:20px;
      margin-right:20px;
      text-align:center;
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child">child</div>
  </div>
</body>

</html>

当居中 div 宽度固定时

1. 设置左右外边距值为auto

margin: 0 auto;
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    .parent {
      width: 200px;
      height: 300px;
      background: #f60;
      border:7px solid black;
    }
    .child {
      outline:5px solid green;
      width:100px;
      margin: 0 auto;
      text-align:center;
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child">child</div>
  </div>
</body>

</html>

2. 行内元素 + text-align

    .parent {
      text-align:center;
    }
    .child {
      display:inline-block;                                                                                                                                                                                                                                                                                                                                                                       
    }
<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <style>
    .parent {
      width: 200px;
      height: 300px;
      background: #f60;
      border:7px solid black;
      text-align:center;
    }
    .child {
      display:inline-block;
      outline:5px solid green;
      width:100px;
      height:100px;
    }
  </style>
</head>

<body>
  <div class="parent">
    <div class="child">child</div>
  </div>
</body>

</html>

相关文章

网友评论

      本文标题:CSS 水平居中

      本文链接:https://www.haomeiwen.com/subject/fcbuiktx.html