css元素水平垂直居中的几种方法

1.元素水平居中

水平居中最好用的就是

 margin: 0 auto

居中没有效果的原因
1.元素没有设置宽度,没有宽度,肯定是无法居中的
2.设置了宽度仍然无法居中,你设置的是行内元素,只有是块级元素才有用

实例:

<div class="father">
	   <div class="son"></div>	
	</div>

    <style>
    	.father{
    		height: 300px;
    		width: 100%;
    		background-color: blue;
    	}
    	.son{
    		height: 100px;
    		width: 200px;
    		margin: 0 auto;
    		background-color: green;
    	}
    </style>

效果:
在这里插入图片描述

2.元素水平垂直居中

方法一:position元素已知宽高
父元素 position:relative
子元素 position:absolute top:50% left:50% margin-left:-自身宽度的一半 margin-top:-自身高度的一半

实例:

<div class="father">
	   <div class="son"></div>	
	</div>

    <style>
    	.father{
    		position: relative;
    		height: 300px;
    		width: 50%;
    		background-color: blue;
    	}
    	.son{
    		position: absolute;
    		top: 50%;
    		left: 50%;
    		margin-left: -100px;
    		margin-top: -50px;
    		height: 100px;
    		width: 200px;
    		background-color: green;
    	}
    </style>

效果图:
在这里插入图片描述
方法二:子元素宽高未知
父元素:position:relative
子元素:position:absolute top:50% left:50% transform:translate(-50%,-50%)

实例:

<div class="father">
	   <div class="son"></div>	
	</div>

    <style>
    	.father{
    		position: relative;
    		height: 300px;
    		width: 50%;
    		background-color: blue;
    	}
    	.son{
    		position: absolute;
    		top: 50%;
    		left: 50%;
    		transform: translate(-50%,-50%);
    		height: 100px;
    		width: 200px;
    		background-color: green;
    	}
    </style>

效果:
在这里插入图片描述
方法三:flexbox布局
父元素 display:flex justify-content:center align-items:center

实例:

  <div class="father">
	   <div class="son"></div>	
	</div>

    <style>
    	.father{
    		display: flex;
    		justify-content: center; /* 使子项目水平居中 */
            align-items: center; /* 使子项目垂直居中 */
    		height: 300px;
    		width: 50%;
    		background-color: blue;
    	}
    	.son{
    		height: 100px;
    		width: 200px;
    		background-color: green;
    	}
    </style>

效果:
在这里插入图片描述


版权声明:本文为shuoxi666原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。