css水平垂直或者上下左右居中

实现child的宽高不知道的情况下相对于father上下左右或者水平垂直居中,每一种都亲测可用,直接复制记事本中,重命名(*.html)用浏览器打开即可

第一种:利用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">
		<span></span>
		<div style="background: red;" class="child">上下左右</div>
	</div>
</body>
</html>



 
 

猜你喜欢

转载自blog.csdn.net/xufeiayang/article/details/80075040
今日推荐