css常用元素水平垂直居中方案
网站建设 2023-01-28 21:38www.1681989.com免费网站
适用场景父子宽高都可未知(比较推荐这种方式,简单,而且目前兼容性也不错。)
<html> <head> <style> .parent { width: 100%; height: 100px; background: cyan; display: flex; justify-content: center; align-items: center; } .son { width: 20%; height: 20%; background: pk; } </style> </head> <body> <div class='parent'> <div class='son'></div> </div> </body> </html>
适用场景父元素宽高已知未知都行,得有宽高。子元素的宽高必须已知,因为需要设置子元素的负marg. (也可以将负marg设置成translate来做位移实现)
<html> <head> <style> .parent { position: relative; width: 200px; height: 200px; background: pk; } .son { position: absolute; left: 50%; : 50%; marg-left: -25px; marg-: -25px; width: 50px; height: 50px; background: yellow; } </style> </head> <body> <div class='parent'> <div class='son'></div> </div> </body> </html>
适用场景父子元素宽高都未知的情况(该方式不需要明确知道子元素宽高,子元素宽高可用百分比,对于子元素宽高不确定需要居中的情况比较适合。)
<html> <head> <style> .parent { position: relative; width: 200px; height: 200px; background: cyan; } .son { position: absolute; left: 0; : 0; bottom: 0; right: 0; marg: auto; width: 10%; height: 10%; background: yellow; } </style> </head> <body> <div class='parent'> <div class='son'></div> </div> </body> </html>
适用场景父子元素宽高未知,兼容性不大好
<html> <head> <style> .parent { display: grid; } .son { jusitify-self: center; align-self: center; } </style> </head> <body> <div class='parent'> <div class='son'></div> </div> </body> </html>
适用场景: 父元素大小已知(非百分比高度),子元素大小未知,但子元素须为行内块元素,较好的兼容性
<html> <head> <style> .parent { display: table-cell; vertical-align: middle; text-align: center; width: 100vw; height: 90vh; background-color: yellowgreen; } .son { display: le-block; width: 200px; height: 200px; background-color: Indigo; } </style> </head> <body> <div class='parent'> <div class='son'></div> </div> </body> </html>
适用场景父子宽高都可未知,子元素需为行内块元素(这种方式其实就是使用伪元素的高度为100%,子元素和伪元素都设置 vertical-align: middle实现垂直居中的效果)
<html> <head> <style> .parent { height: 100vh; width: 100vw; text-align: center; background: #c0c0c0; } .parent:before { content: "\200B"; display: le-block; height: 100%; vertical-align: middle; } .son { display: le-block; vertical-align: middle; width: 200px; height: 200px; paddg: 10px 15px; background: #f5f5f5; } </style> </head> <body> <div class="parent"> <div class="son"></div> </div> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
网站设计
- 静宁会SEO的网站建设公司:全面提升您的网络影
- 提升在线业务的关键:选择最佳的丽水网站建设
- 浙江网站优化发展潜力如何
- 井研专业的网站建设公司:打造您的在线品牌
- 灵山SEO网站建设公司:提升您的在线业务表现
- 蒙城网站建设优化公司:提升您网站表现的理想
- 阳谷企业网站优化:提升线上业务力的关键
- 樟树专业的网站建设公司:打造您在线业务的坚
- 通河百度SEO排名的策略与技巧
- 重庆百度快照排名如何进行精准的客户引流
- 重庆百度快照排名
- 常宁便宜的建站公司:助您轻松打造在线业务
- 巫溪百度网站优化:提升网站曝光率与流量的关
- 湖北整站优化怎么做才能放大客户需求
- 闸北网站建设多少钱?全面解析与预算规划
- 辽宁企业网站优化怎么做电话营销