欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

CSS让子元素快速水平垂直居中的几种方法

程序员文章站 2022-04-30 12:09:45
...

方法有很多这里列出几种常用的
CSS代码如下 父元素类名以out打头,子元素类名以in打头 one,two…代表不同的方法

<style>
	*{
		padding: 0;
		margin: 0;
	}
	[class*=out]{
		width: 200px;
		height: 200px;
		background-color: pink;
		margin: 20px;
	}
	[class*=in]{
		width: 100px;
		height: 100px;
		background-color: black;
	}
	.out-one{
		display: table-cell;
   		vertical-align: middle;
        text-align: center;
	}
	.in-one{
		display: inline-block;
		vertical-align: middle;
	}
	.out-two{
		position: relative;
	}
	.in-two{
		position: absolute;
		margin: auto;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
	}
	.out-three{
		position: relative;
	}
	.in-three{
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%,-50%);
	}
	.out-four{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.in-four{

	}
	.out-five{
		display: flex;
	}
	.in-five{
		margin: auto;
	}
	.out-six{
		position: relative;
	}
	.in-six{
		position: absolute;
		left: 50%;
		top: 50%;
		margin-left: -50px;
		margin-top: -50px;
	}
</style>

HTML代码

<body>
	<!-- display:table-cell -->
	<div class="out-one">
		<div class="in-one"></div>
	</div>

	<!-- position + margin -->
	<div class="out-two">
		<div class="in-two"></div>
	</div>

	<!-- position + transform -->
	<div class="out-three">
		<div class="in-three"></div>
	</div>

	<!-- display:flex align-items: center;justify-content: center -->
	<div class="out-four">
		<div class="in-four"></div>
	</div>

	<!-- display:flex margin:auto -->
	<div class="out-five">
		<div class="in-five"></div>
	</div>

	<!-- position -->
	<div class="out-six">
		<div class="in-six"></div>
	</div>


</body>