CSS 常用的三种居中定位布局

嗨,我是小路。今天主要和大家分享的主题是""。

一、三种常用布局

1.子绝父相 margin 居中

注意:父级相对定位,子级绝对定位,并且子级margin-left,margin-top是负值,为宽度、高度的一半。

css 复制代码
/** 子绝父相 margin 居中 */
	.father{
		position: relative;
		width: 500px;
		height: 500px;
		margin: 0 auto;
		border: 1px solid;
		.son{
			position: absolute;
			left: 50%;
			top: 50%;
			margin-left: -100px;//负值,宽度的一半
			margin-top: -50px;//负值,高度的一半
			width: 200px;
			height: 100px;
			background: yellow;
		}
	}

2.子绝父相 transform 居中

注意:父级相对定位,子级绝对定位,并且子级transform:translate(-50%,-50%),为宽度、高度的一半。

css 复制代码
/** 子绝父相 transform 居中 */
	.father1{
		position: relative;
		width: 500px;
		height: 500px;
		margin: 0 auto;
		border: 1px solid;
		.son1{
			position: absolute;
			left: 50%;
			top: 50%;
			transform: translate(-50%,-50%);//负值,横向 竖向移动一半距离
			width: 200px;
			height: 100px;
			background: blue;
		}
	}

3.弹性盒子flex

注意:设置盒子为弹性盒子,主轴和侧轴必须是center。子级任意高宽,不超出父级即可。

css 复制代码
/** flex 居中 */
	.father2{
		display: flex;
		justify-content: center;
		align-items: center;

		width: 500px;
		height: 500px;
		margin: 0 auto;
		border: 1px solid;
		.son2{
			
			width: 200px;
			height: 100px;
			background: green;
		}
	}

目前三种类型中,用的最多的布局是flex。

嗨,我是小路。如果这篇文章对你有帮助,记得【点赞】+【关注】哟。

相关推荐
GISer_Jing2 小时前
前端面试通关:Cesium+Three+React优化+TypeScript实战+ECharts性能方案
前端·react.js·面试
落霞的思绪3 小时前
CSS复习
前端·css
咖啡の猫5 小时前
Shell脚本-for循环应用案例
前端·chrome
百万蹄蹄向前冲7 小时前
Trae分析Phaser.js游戏《洋葱头捡星星》
前端·游戏开发·trae
朝阳5818 小时前
在浏览器端使用 xml2js 遇到的报错及解决方法
前端
GIS之路8 小时前
GeoTools 读取影像元数据
前端
ssshooter9 小时前
VSCode 自带的 TS 版本可能跟项目TS 版本不一样
前端·面试·typescript
Jerry9 小时前
Jetpack Compose 中的状态
前端
dae bal10 小时前
关于RSA和AES加密
前端·vue.js
柳杉10 小时前
使用three.js搭建3d隧道监测-2
前端·javascript·数据可视化