一、先确定div的基本样式

先给div随便设置些基本的样式,这样所得到的结果容易看出效果。

css结构:
	<style type="text/css">
		*{
			margin: 0;
			height: 0;
		}
		.warp{
			width: 500px;
			height: 500px;
			background-color: pink;//给个背景,结果更清晰
			margin: 50px auto;
		}
		.warp .box{
			width: 200px;
			height: 200px;
			background-color: green;
		}
	</style>
HTML结构:
	<div class="warp">
		<div class="box"></div>
	</div>

二、具体实现方法

第一种:利用子绝父相和margin: auto实现

给父级div设置相对定位,子元素div设置绝对定位,left、right、top、bottom都设置为0,然后将margin设置为auto即可实现。

注意:子绝父相就是 父级元素相对定位,子级元素绝对定位

		.warp{
			width: 500px;
			height: 500px;
			background-color: pink;
			margin: 50px auto;
    		
    		position:relative;//设置为相对定位
		}
		.warp .box{
			width: 200px;
			height: 200px;
			background-color: green;
            
            position:absolute;//设置为绝对定位
            left: 0;
      		right: 0;
      		top: 0;
      		bottom: 0;
     		margin: auto;
		}
第二种:利用子绝父相和过渡动画tranform实现

给父级div设置相对定位,子元素div设置绝对定位,将left、top设置为50%;然后设置transform: translate(-50%,-50%);即可实现。

原理:设置了left: 50%;top:50%; 之后,子元素位于如图所在位置,在这里插入图片描述
此时,我们需要向左移动子级div宽度的一半,子级div所在位置如图所示在这里插入图片描述
向上移动子级div高度的一半,结果如图所示在这里插入图片描述
transform: translate(-50%,-50%);

		.warp{
			width: 500px;
			height: 500px;
			background-color: pink;
			margin: 50px auto;
    		
    		position:relative;//设置为相对定位
		}
		.warp .box{
			width: 200px;
			height: 200px;
			background-color: green;
            
            position:absolute;//设置为绝对定位
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
		}
第三种:同样是利用子绝父相和margin负值实现

子级div设置绝对定位,同样设置left: 50%; top: 50%,然后利用margin值为负时,产生的相反位移(同上过渡动画tranform产生位移类似)。即margin-left:calc(-div自身宽度/2),margin-top:calc(-div自身高度/2),也可以自己计算margin-left 和 margin-top的值。

注意:calc()函数,CSS3 的 calc() 函数允许我们在属性值中执行数学计算操作。

		.warp{
			width: 500px;
			height: 500px;
			background-color: pink;
			margin: 50px auto;
    		
    		position:relative;//设置为相对定位
		}
		.warp .box{
			width: 200px;
			height: 200px;
			background-color: green;
            
            position:absolute;//设置为绝对定位
            left: 50%;
            top: 50%;
			margin-left:calc(-200px/2);
			margin-top:calc(-200px/2);	
		}
第四种:利用flex弹性盒布局实现

给父级div设置display: flex;将父级div元素转为弹性盒,然后设置主轴对齐方式为居中 justify-content: center;,侧轴对齐方式为居中 align-items: center;即可实现。

		.warp{
			width: 500px;
			height: 500px;
			background-color: pink;
			margin: 50px auto;
			
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.warp .box{
			width: 200px;
			height: 200px;
			background-color: green;
		}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐