子div上下居中:top:50%;margin-top:-h/2; 或是 bottom:50%;margin-bottom:-h/2;;
子div左右居中: left:50%;margin-left:-w/2 或是 right:50%;margin-right:-w/2;
例子<style>
* {margin: 0; padding: 0; box-sizing: border-box;}
.father {position: relative;}
.son {position: absolute;bottom:50%;margin-bottom: -50px;left: 50%;margin-left: -50px;
}
</style>
<body>
<div class=\”father\” style=\”width: 100%; height: 400px; border: 1px solid rebeccapurple;\”>
<div class=\”son\” style=\”width: 100px; height: 100px;background: palegreen;\”></div>
</div>
</body>方法四(定位)理念:
定位属性top和bottom(或是left和right)值分别设置为0,但子div有固定高度(宽度),并不能达到上下(左右)间距为0,此时给子div设置margin:auto会使它居中显示 。
步骤:
父div标记下定位(position:relative|absolute|fixed|sticky);子div绝对定位(position:absolute)
子div上下居中:top:0;bottom:0;margin-top:auto;margin-bottom:auto
子div左右居中:left:0;right:0;margin-left:auto;margin-right:auto
例子<style>
* {margin: 0; padding: 0; box-sizing: border-box;}
.father {position: relative;}
.son {position: absolute; top: 0; bottom:0; left: 0; right: 0; margin: auto}
</style>
<body>
<div class=\”father\” style=\”width: 100%; height: 400px; border: 1px solid rebeccapurple;\”>
<div class=\”son\” style=\”width: 100px; height: 100px;background: palegreen;\”></div>
</div>
</body>方法五(flex)理念
弹性盒子,自带的一个居中功能
例子<style>
* {margin: 0; padding: 0; box-sizing: border-box;}
.father {display: flex; align-items: center}
.son {margin: auto}
</style>
<body>
<div class=\”father\” style=\”width: 100%; height: 400px; border: 1px solid rebeccapurple;\”>
<div class=\”son\” style=\”width: 100px; height: 100px;background: palegreen;\”></div>
</div>
</body>
flex兼容性,以及存在的已知问题
结尾
方法二和方法三兼容性要比其它好些
参考资料
Can I usecss-vertical-center-solutionCSS实现垂直居中的5种方法–前端观察
(今完)
推荐阅读
- 怎么在电脑上下载免费的字体 下载字体如何安装
- 集中供暖能单独停一户吗 楼房供热报停对上下左右住户影响多大
- wps居中快捷键是哪个
- 原神星盘怎么对齐
- excel上下两个三角 excel上下两行合并一行
- word调整字间距两行对齐 word调整字间距
- 新手烤面包上下火温度120度 新手烤面包上下火温度
- 优酷转码mp4 优酷转码
- 合并居中快捷键ctrl加什么
- 河流怎么分上下游
