实现居中的CSS方法

  在实际开发过程中,元素居中是常用的布局之一,为此特别整理了几种居中方式:

  一、table-cell

  先看看html文档结构:

<div class="show show1">
    <p>1、垂直居中</p>
</div>

  再看看css样式,因为例子比较多,基础样式都为都为show,后面不再重复了

.show{
    width: 200px;
    height:200px;
    background: #999;
    margin: 25px;
}
.show1{
    display: table-cell;
    vertical-align:middle;
    text-align: center;
}

在浏览器中打开我们可以看到:

  这边需要注意:

     1、table-cell不感知margin,我在基础样式中添加了margin值,在浏览器开发工具中看不到margin有值。

     2、设置float或position会对默认布局造成破坏,可以考虑为之增加一个父div定义float等属性。

二、display:flex

  html文档结构几乎一样不再重复,直接看css样式:

.show2{
    display:flex;
    justify-content: center;
    align-items: center;
}

  相比第一个例子,这边的margin值得以体现。

 三、绝对定位和负边距

html文档结构:

<div class="base show show3">
    <p>3、绝对定位和负边距</p>
</div>

css样式:

.base{
    position:relative;
}
.show3 p{
    position:absolute;
    width:100px;
    height:50px;
    top:50%;
    left:50%;
    margin-left:-50px;
    margin-top:-25px;
    text-align: center;
    background-color: #007AFF;
}

结果如图所示:

四、绝对定位和0

css样式:

.show4 p{
    position: absolute; 
    width: 50%;
    height: 50%;
    overflow:auto; 
    margin:auto;
    text-align: center;
    top: 0; left: 0; bottom: 0; right: 0; 
    background-color: #007AFF;
}

结果:

 

 

  

转载于:https://www.cnblogs.com/lwxiao/p/10275899.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值