HTML Div Center
在HTML中,我们经常会用到<div>元素来组织和布局网页内容。而要让<div>元素水平居中显示,可以通过不同的方法来实现。本文将介绍几种常用的方法来让<div>元素在页面上水平居中显示。
方法一:使用CSS的text-align:center
通过设置父元素的text-align属性为center,可以让其子元素水平居中显示。
<!DOCTYPE html>
<html>
<head>
  <style>
    .center {
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="center">
    <p>how2html.com</p>
  </div>
</body>
</html>
Output:

方法二:使用CSS的margin:auto
通过设置<div>元素的左右margin为auto,可以让其在页面上水平居中显示。
<!DOCTYPE html>
<html>
<head>
  <style>
    .center {
      margin: 0 auto;
      width: 50%;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="center">
    <p>how2html.com</p>
  </div>
</body>
</html>
Output:

方法三:使用CSS的flexbox
通过使用CSS的flexbox布局来让<div>元素水平居中显示。
<!DOCTYPE html>
<html>
<head>
  <style>
    .container {
      display: flex;
      justify-content: center;
    }
  </style>
</head>
<body>
  <div class="container">
    <div>how2html.com</div>
  </div>
</body>
</html>
Output:

方法四:使用CSS的position和transform
通过设置<div>元素的position属性为absolute,然后使用transform属性来实现水平居中显示。
<!DOCTYPE html>
<html>
<head>
  <style>
    .center {
      position: absolute;
      left: 50%;
      transform: translateX(-50%);
    }
  </style>
</head>
<body>
  <div class="center">
    <p>how2html.com</p>
  </div>
</body>
</html>
通过上述几种方法,我们可以轻松实现<div>元素在页面上的水平居中显示。
极客笔记