不定宽高元素的上下左右居中

实现child的宽高不知道的情况下相对于father上下左右或者水平垂直居中,每一种都亲测可用
第一种:利用display:flex;最简单的一种

<!DOCTYPE html>
<html lang="en">
<head></head>
<style type="text/css">
    .father{
        background: green;
        height: 500px;
        width: 500px;
        display: flex;
        justify-content: center;
        align-items: center;
    }
    .child{
        background: red;
    }
</style>
<body>
    <div class="father">
        <div class="child">上下左右</div>
    </div>

</body>
</html>

第二种办法:使用display:table-cell

<!DOCTYPE html>
<html lang="en">
<head></head>
<style type="text/css">
	.father{
		background: green;
		height: 500px;
		width: 500px;
		display:table-cell;
        text-align:center;
        vertical-align:middle;
	}
	.child{
		display:inline-block;
	}
</style>
<body>
	<div class="father">
		<div style="background: red;" class="child">上下左右</div>
	</div>
</body>
</html>

第三种 使用参照物如:增加一个span或者其他元素

<!DOCTYPE html>
<html lang="en">
<head></head>
<style type="text/css">
	.father{
		background: green;
		height: 500px;
		width: 500px;
		text-align: center;
	}
	.father span{
        display:inline-block;
        vertical-align:middle;
        height:100%;
    }
	.child{
		 display:inline-block;
         vertical-align:middle;
	}

</style>
<body>
	<div class="father">
		<span></span>
		<div style="background: red;" class="child">上下左右</div>
	</div>
</body>
</html>

第四种:使用 transform:translate(-50%,-50%)拉回自身宽高50%;

<!DOCTYPE html>
<html lang="en">
<head></head>
<style type="text/css">
	.father{
    		background: green;
    		height: 500px;
    		width: 500px;
    		position: relative;
	}
	.child{
            position:absolute;
            left:50%;
            top:50%;
            transform:translate(-50%,-50%);
	}

</style>
<body>
	<div class="father">
		<div style="background: red;" class="child">上下左右</div>
	</div>
</body>
</html>

第5种 display: grid

<!DOCTYPE html>
<html lang="en">
<head></head>
<style type="text/css">
	.father{
		background: green;
		height: 500px;
		width: 500px;
		display: grid;
	}
	.child{
	    justify-self: center;
    	align-self: center;
	}

</style>
<body>
	<div class="father">
		<div style="background: red;" class="child">上下左右</div>
	</div>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值