网页元素居中攻略记_(1)元素水平居中

行内元素水平居中

方案

  • 行内元素包裹在一个属性displayblock的父层元素中,父块text-align:center即可实现

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">

  <head>
    <meta charset="UTF-8">
    <title>行内元素水平居中</title>
    <style type="text/css">
      p {
        display: ineline-block;
      }

      .testDiv {
        text-align: center;
        width: 500px;
        height: 500px;
        background: rgb(78, 243, 145);
      }

      /*
      适用元素:文字,链接,及其其它inline或者inline-*类型元素(inline-block,inline-table,inline-flex)
       */

    </style>
  </head>

  <body>
    <div class="testDiv">
      <span>我是测试文本</span>
      <b>|我也是</b>
      <p>我也是测试的啊</p>
    </div>
  </body>

</html>

一个块状元素水平居中

方案

设置块的margin为左右为auto即可,上下margin可以根据需求设置{margin:0 auto}

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">

  <head>
    <meta charset="UTF-8">
    <title>一个块元素水平居中</title>
    <style type="text/css">
      #container {
        width: 800px;
        height: 800px;
        background: rgb(129, 97, 53);
        margin: 0 auto;
      }
      

    </style>
  </head>

  <body>
    <div id="container">

    </div>
  </body>

</html>

多个块状元素水平居中

方案

  • 参考第一个实现,内部DIV设置为内联块,包裹块设置text-align:center

代码实现

index.html

<!DOCTYPE html>
<html lang="zh">

  <head>
    <meta charset="UTF-8">
    <title>多个块元素水平居中</title>
    <style type="text/css">
      #container {
        text-align: center;
        background: rgb(26, 188, 130);
        width: 500px;
        height: 500px;
      }

      #testDiv1 {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: #03232A;
      }

      #testDiv2 {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: #122A03;
      }

      #testDiv3 {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: #189FBD;
      }

      #testDiv4 {
        display: inline-block;
        width: 100px;
        height: 100px;
        background: #E20FAD;
      }

    </style>
  </head>

  <body>
    <div id="container">
      <div id="testDiv1"></div>
      <div id="testDiv2"></div>
      <div id="testDiv3"></div>
      <div id="testDiv4"></div>
    </div>
  </body>

</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

crper

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值