Html+CSS_居中布局的总结

来源:互联网 发布:linux 系统 死机 日志 编辑:程序博客网 时间:2024/04/30 02:44

学前端有一段时间了,居中布局是日常经常遇到的问题,在此对居中布局进行一个总结。



水平居中





垂直居中


1.



2.




3.利用定位(position)实现 水平 垂直 居中


根据 CSS权威指南 中对浮动元素的一些定位性质:

在父元素不受限的情况下:

父元素的width =  子元素width + 子元素padding + 子元素border-width+子元素margin + 子元素left + 子元素right  

父元素的height =  子元素height + 子元素padding + 子元素border-width+子元素margin + 子元素top + 子元素bottom  

以上等式恒成立


可以通过将子元素left,right  / top,bottom 等给定(设置为0),margin设置为auto, 让浏览器自己计算margin的值。根据等式恒成立的性质  

将margin-left=margin-right   /  margin-top=margin-bottom 从而达到居中的特点:


示例代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>利用margin:auto 0;垂直居中定位</title>    <style type="text/css">        .father{            position: relative;            width:500px;            height:500px;            background-color: gold;        }        .son{            right:0;            left:0;            top:0;            bottom: 0;            position: absolute;            margin: auto auto;            width:200px;            height:200px;            background-color: #6d8ab7;        }    </style></head><body>    <div class="father">        <div class="son">        </div>    </div></body></html>

效果截图:





 





0 0
原创粉丝点击