CSS3垂直水平的居中的几种方法

一、利用绝对定位居中

           方法:利用 position: absolute; 相对于父级元素进行绝对定位,对 top 、left 、right 、bottom 等的值进行操控来实现。具体代码如下所示:

           1、margin: auto; 方法

{
  width: 100px;
  height: 100px;
  border: 1px solid green;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}

           2、改变 margin 值

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

.body{
  width: 500px;
  height: 500px;
  border: 1px solid #000;
  position: relatuve;
}
.center{
  width: 100px;
  height: 100px;
  border: 1px solid green;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -50px;
}

二、利用弹性盒子居中

           方法:元素 display 定义为 flex 。利用 fiexd 容器和容器内项目 item 的关系属性进行垂直居中。具体代码如下:

           1、容器直接让项目垂直居中

<div class="body" >
  <div class="content"></div>
</div>
.body{
  width: 500px;
  height: 500px;
  border: 1px solid red;
  display: flex;
  justify-content: center;
  align-items: center;
}
.content{
  width: 100px;
  height: 100px;
  border: 1px solid green;
}

          2、容器先让项目水平居中,项目自身要求居中

<div class="body" >
  <div class="content" ></div>
</div>
.body{
  width: 500px;
  height: 500px;
  border: 1px solid red;
  display: flex;
  justify-content: center;
}
.content{
  width: 100px;
  height: 100px;
  border: 1px solid green;
  align-self: center;
}

三、利用行高对文本垂直居中

           方法:设置文本 line-height 值和容器高度一致,然后 text-align: center; 具体代码如下:

<div class="inText" >
  我的猫猫叫粪球
</div>

.inText{
  width: 500px;
  height: 300px;
  line-height: 300px;
  text-align: center;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值