HTML+CSS元素水平垂直居中<6种>

HTML+CSS 元素水平垂直居中<6种>

首先初始化一个盒子

<body>
  <div class="box"></div>
</body>

<style>
    * {
      margin: 0;
      padding: 0;
    }

    html,body {
      width: 100%;
      height: 100%;
    }

    .box {
      width: 200px;
      height: 200px;
      background-color: aquamarine;
    }
</style>

请添加图片描述

第1种方法:绝对定位(absolute)和margin:auto实现

<body>
  <div class="box pos-1"></div>
</body>
/* 另添加pos-1类 */
/*绝对定位(absolute)和margin:auto实现 */
 .pos-1 { 
      position: absolute;
      left: 0;
      top: 0;
      right: 0;
      bottom: 0;

      margin: auto; 
} 

请添加图片描述

第2种方法:绝对定位(absolute)和回退自身宽高一半

<body>
  <div class="box pos-2"></div>
</body>
/* 另添加pos-2类 */
/* 2.绝对定位(absolute)和回退自身宽高一半 */
    .pos-2 { 
      position: absolute;
      left: 50%;
      top: 50%;

      margin-left: -100px; 
      margin-top: -100px;

    }

请添加图片描述

第3种方法:绝对定位(absolute)和transform

 <body>
  <div class="box pos-3"></div>
</body>
/* 另添加pos-3类 */
/* 3.绝对定位(absolute)和transform */
    .pos-3 { 
      position: absolute;
      left: 50%;
      top: 50%;

      transform: translate(-50%,-50%); 
    }

请添加图片描述

第4种方法:flex布局 justify-content和align-items

 <body>
  <div class="box pos-4"></div>
</body>
/* 另添加pos-4类 */
/* 4.flex布局 justify-content和align-items */
	html,body {
      width: 100%;
      height: 100%;

	  /* 另添加属性 */
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .pos-4 { 
      不用写,不用另添加类,修改其 父类(body)
    }

请添加图片描述

第5种:文本水平垂直居中text-align+line-height

<body>
  <div class="box pos-5">这是一首简单的小情歌</div>
</body>

/* 另添加pos-5类 */
/* 5.文本垂直居中 */
	.pos-5 {
      text-align: center;
      line-height: 200px;  //设定值与其自身height一样
    }

请添加图片描述

第6种:盒子不设宽高,inline-block+padding

<body>
  <div class="box pos-6">这是一首简单的小情歌</div>
</body>

/* 另添加pos-6类 */
/* 6.文本垂直居中 */
	.box {
      /* width: 200px;
      height: 200px; */
      background-color: aquamarine;
      
      /*新增属性*/
	  display: inline-block;
    }
	.pos-6 {
      padding: 20px;
    }

请添加图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值