3

CSS水平居中

 2 years ago
source link: https://www.longdw.com/1177.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

CSS水平居中

如果要设置块级元素水平居中,比如div、p,只需要设置margin:0 auto即可。

如下html,要设置div水平居中:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>块级盒子水平居中</title>
<!-- 块级盒子水平居中,需要满足:1.必须指定宽度。2.盒子左右外边距都设置为auto。 -->
<style>
.header {
width: 900px;
height: 200px;
background-color: pink;
margin: 0 auto;
</style>
</head>
<body>
<div class="header"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>块级盒子水平居中</title>
  <!-- 块级盒子水平居中,需要满足:1.必须指定宽度。2.盒子左右外边距都设置为auto。 -->
  <style>
    .header {
      width: 900px;
      height: 200px;
      background-color: pink;
      margin: 0 auto;
    }
  </style>
</head>

<body>

  <div class="header"></div>

</body>

</html>

如果要设置行内元素或行内块元素水平居中,只需要在父级元素上设置text-align: center即可。

如下html,要设置span水平居中,只需要在父元素div上设置text-align: center

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>行内元素水平居中</title>
<style>
/* 如果要让行内元素如img、span等水平居中,只需要给父元素添加上text-align:center就好。 */
.header {
width: 900px;
height: 200px;
background-color: pink;
margin: 100px auto;
/* 加上这句话就好 */
text-align: center;
</style>
</head>
<body>
<div class="header">
<span>这是里面的文字</span>
</div>
<div class="header">
<img src="../images/avatar.png"></img>
</div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>行内元素水平居中</title>
  <style>
    /* 如果要让行内元素如img、span等水平居中,只需要给父元素添加上text-align:center就好。 */
    .header {
      width: 900px;
      height: 200px;
      background-color: pink;
      margin: 100px auto;
      /* 加上这句话就好 */
      text-align: center;
    }
  </style>
</head>

<body>

  <div class="header">
    <span>这是里面的文字</span>
  </div>

  <div class="header">
    <img src="../images/avatar.png"></img>
  </div>

</body>

</html>



About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK