CSS实现居中的各种方法

使用CSS实现元素居中在实际应用中非常常见,下边我说一下我所总结的几个实现元素居中的方法。

html基本代码
	<div class="father">
        <div class="child"></div>
    </div>
css基本代码
	* {
    	margin: 0;
        padding: 0;
    }
    .father {
        width: 100%;
        height: 600px;
        background-color: #8d8d8d;
    }
方法一

使用position: absolute 和 transform实现居中,此时父级应有position: relative属性

	.child {
        width: 300px;
        height: 300px;
        background-color: red;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%,-50%);
    }
方法二

使用position: absolute 和 margin、left、right实现居中,此时父级应有position: relative属性

	.child {
		width: 300px;
        height: 300px;
        background: red;
        position: absolute;
        left: 50%;
        top: 50%;
        margin-left: -150px;
        margin-top: -150px;
    } 
方法三

设置上下左右都为0,并使用margin auto实现居中,此时父级应有position: relative属性

	.child {
		width: 300px;
        height: 300px;
        background: red;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        right: 0;
        margin: auto;
    } 
方法四

通过relative和margin auto实现,此时父级需要设置overflow:hidden(将父级设置为BFC)

	.child {
		position: relative;
        width: 300px;
        height: 300px;
        margin: 150px auto;
        background: red;
    } 
方法五

使用display: flex,align-items: center,justify-content: center

	.father {
		display: flex;
        align-items: center;
        justify-content: center;
    }
    .child {
        width: 300px;
        height: 300px;
        background: red;
    }
方法六

使用display: flex,margin: auto

	.father {
		display: flex;
    }
    .child {
        margin: auto;
        width: 300px;
        height: 300px;
        background: red;
    } 
方法七

元素内部字体实现居中方法

	<div class="father">
        <div class="child">
        	<p>hello</p>
        </div>
    </div>
	.child {
      	display: table-cell;
       	vertical-align: middle;
       	text-align: center;
       	width: 300px;
       	height: 300px;
       	background: red;
    } 
方法八

使用calc函数,其中的“-”两边必须加上空格,相减数为当前元素宽高

	.child {
		position: absolute;
        width: 300px;
        height: 300px;
        left: calc(("当前屏幕像素" - 300px)/2);
        top: calc((600px - 300px)/2);
        background: red;
    } 

本人才疏学浅,如有不对之处,烦请指正,如果各位有其他方法,烦请在评论区多多交流。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值