Css 居中处理方式

text-align:center方式

<div class="center">
  <span class="center_text">
    123
  </span>
</div>
.center{
  text-align:center;
}
center_text{
  display:inline-block;
  width:500px
}

margin:auto方式

<div class="center">
  <span class="center_text">
    我是块级元素,我是块级元素,我给自己设了display:block
  </span>
</div>
center_text{
  display:block;
  width:500px;
  margin:0 auto;
}

脱离文档流的居中方式。

这种通常应用在自定义弹框当中,把背景层设置成透明灰色,内容居中显示在最前面。

<div class="mask">
  <div class="content"><br>    我是要居中的板块
  </div>
</div>
.mask{
  display: block;
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  filter: alpha(opacity=30);
  -ms-filter: "alpha(opacity=30)";
  opacity: .3;
  z-index: 10000;
}
.center{
    display: block;
    position: fixed;
    _position: absolute;
    top: 50%;
    left: 50%;
    width: 666px;
    height:400px;
    margin-left: -333px;
    margin-top: -200px;
    z-index: 10001;
    box-shadow: 2px 2px 4px #A0A0A0, -2px -2px 4px #A0A0A0;
    background-color: #fff;
}

元素的垂直居中

把height和line-height的值设置成一样的即可。

<div class="center">
  <span class="center_text">
    我是要居中的内容<br>  </span>
</div>
center{
  height:40px;
  line-heigth:40px;
}

使用css3的translate水平垂直居中元素

<div class="center">
  <div class="center_text">
    我是要居中的内容<br>  
  </div> 
</div>
.center {
    position: relative;
    height: 500px;}
.center_text{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
    height: 600px;
}

这种方式将脱离文档流的元素,设置top:50%,left:50%,然后使用transform来向左向上便宜半个内元素的宽和高。

使用css3计算的方式居中元素calc

.center {
    position: relative;
    height: 300px;
    width: 1000px;
    border: 1px solid #ccc;
}
.center_text{
    position: absolute;
    top: calc(50% - 50px);
    left: calc(50% - 150px);
    width: 300px;
    height: 100px;
    border: 1px solid #000;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值