方法:定位,外边距,内边距,层级,边框;一个元素;两个元素;三个元素.<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://www.huyubaike.com/biancheng/index.css"></head><body> <div class="father1"> <div class="son1"></div> </div>方法1
<div class="father2"> <div class="son2"></div> </div>方法2
<div class="father3"> <div class="son3"></div> </div>方法3
<div class="father4"> <div class="son4"></div> </div>【HTML&CSS-盒模型运用居中方式合集】方法4
<div class="father5"> <div class="son5"></div> </div> <!-- 前五种为两个元素的居中方式 -->方法5
<div class="six"></div>方法6
<div class="seven"></div> <!-- 后两种为1个元素的居中方式 -->方法7
<div class="father8"> <div class="box1"></div> <div class="box2"></div> </div></div> </div> <!-- 最后一种为3个元素的居中方式 -->方法8</body></html> * { margin: 0; padding: 0; list-style: none;}清除浏览器默认样式.father1 { width: 400px; height: 400px; background-color: #fc4; position: relative;}.son1 { width: 200px; height: 200px; background-color: #f44; position: absolute; top: 100px; left: 100px;}/* 第一种居中方式 */定位.father2 { width: 200px; height: 200px; background-color: #f77; position: relative;}.son2 { width: 100px; height: 100px; background-color: #ff7; position: absolute; left: 50%; top: 50%; margin-left: -50px; margin-top: -50px;}/* 第二种居中方式 */定位+外边距+百分比.father3 { width: 200px; height: 200px; background-color: #0f0; position: relative; /* overflow: hidden; */ /* 解决margin塌陷问题 */}.son3 { width: 100px; height: 100px; background-color: #77f; position: absolute; margin-left: 50px; margin-top: 50px;}/* 第三种居中方式 */定位+外边距.father4 { width: 100px; height: 100px; padding: 50px; background-color: #f44;}.son4 { width: 100px; height: 100px; background-color: #0f7;}/* 第四种居中方式 */内边距.father5 { width: 100px; height: 100px; border: 50px solid #f444; background-color: #f444;}.son5 { width: 100px; height: 100px; background-color: #4fff;}/* 第五种居中方式 */边框.six { width: 200px; height: 200px; background-color: #f9f67f; border: 100px solid #08c;}/* 第六种居中方式 */一个元素 边框.seven { width: 0px; height: 0px; padding: 100px; background-color: #f78; border: 50px solid #99f4;}/* 第七种居中方式 */一个元素 边框+内边距.box1 { width: 200px; height: 200px; background-color: #f075; position: absolute; z-index: 1;}.box2 { width: 100px; height: 100px; background-color: #ff99; position: absolute; z-index: 2; top: 50px; left: 50px;}.father8 { position: relative;}/* 第八种居中方式 */3个元素 定位+层级
推荐阅读
- JS 模块化-05 ES Module & 4 大规范总结
- 研发效能之技术治理&技术治理架构师
- 为什么阿里Java开发手册不推荐使用Timestamp
- 古代的"一两白银"相当于现在的多少钱?
- are't的完全形式是什么
- 谁看过我的朋友圈怎么查 谁看过&lt;战争之王&gt;这电影?
- "静坐常思已过,闲谈莫论人非"是出自谁的诗句?
- 剖腹产和顺产坐月子饮食注意事项 剖腹产坐月子饮食注意事项&amp;食谱推荐,值得收藏!
- "漫画"老师作文500字五年级上册(夸张 漫画老师作文500字五年级10篇)
- 《走进科学》 《走进科学》&amp;quot;黄延秋事件&amp;quot;到底谁在撒谎?