什么是布局
html页面的整体结构或骨架,类似于传统的报纸或杂志中的排版
布局不是某个技术内容,而是一种设计思想
居中布局的分类:
水平居中布局,垂直居中布局,居中布局(水平 + 垂直)
什么是水平居中布局
指当前元素在父级元素容器中,水平方向是居中显示的
解决方案
<div class="parent"> <div class="child">我是child</div> </div>
第一种方案:
.parent{ width:100%; height:200px; background:#ccc; /* text-align属性:是为文本内容设置对齐方式 left:左对齐 center:居中对齐 right:右对齐 */ text-align:center; } .child{ width:200px; height:200px; background:#c9394a; /* inline:内联元素(text-align属性有效) 缺点:width和height属性是无效的 inline-block:行内块级元素(块级+内联) */ display:inline-block;/*如果子元素不设置width和height,display:inline*/ }
优点:浏览器兼容性比较好
缺点:text-align属性具有继承性,导致子级元素的文本也是居中显示的
解决方法:给子级元素重新设置text-align:left
第二种方案
.parent{ width:100%; height:200px; background:#ccc; } .child{ width:200px; height:200px; background:#c9394a; display:block;/*display:table; */ /* margin属性:外边距 一个值:上右下左 二个值:第一个值表示上下 第二个值表示左右 auto:表示根据浏览器自动分配 三个值:第一个表示上,第二个表示左右,第三个值表示下 四个值:上右下左 */ margin:0 auto; }
优点:只需要对子级元素进行设置就可以实现水平方向居中布局效果
缺点:如果子级元素脱离文档流,导致margin属性的值无效
脱离文档流的方法:1.float:left / right 2.position:absolute 3.position:fixed
第三种方案
.parent{ width:100%; height:200px; background:#ccc; position: relative; /*absolute,fixed,relative都可以*/ } .child{ width:200px; height:200px; background:#c9394a; /* 当前元素设置为决定定位后: 如果父级元素没有开启定位,当前元素是相对于页面定位的 如果父级元素开启定位,当前元素是相对于父级元素定位 */ position:absolute; left: 50%; transform: translateX(-50%); }
优点:父级元素是否脱离文档流,不影响子级元素水平居中效果
缺点:transform属性是css3中新增属性,浏览器支持情况不好
Believe in yourself