div+css盒子居中
生活随笔
收集整理的這篇文章主要介紹了
div+css盒子居中
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.利用margin
優(yōu)點(diǎn):兼容性好
缺點(diǎn):必須知道內(nèi)容盒子的高度才可以,有了這點(diǎn)限制;
div1的寬減去div2的寬就是div2margin-left的數(shù)值:(100-40)/2=30
div1的高減去div2的高就是div2margin-top的數(shù)值:(100-40)/2=30
2. position+50%
缺點(diǎn):IE6及以上
把div2相對(duì)于div1的top、left都設(shè)置為50%,然后再用margin-top設(shè)置為div2的高度的負(fù)一半拉回來(lái),用margin-left設(shè)置為寬度的負(fù)一半拉回來(lái)
<style type="text/css">.div1{ width: 100px; height: 100px; border: 1px solid #000000;} .div2{ width:40px ; height: 40px; background-color: green;}.div11{position: relative;}.div22{position: absolute;top:50%;left: 50%;margin-top: -20px;margin-left: -20px;}</style><div class="div1 div11"><div class="div2 div22"></div></div>3.position+margin:auto
缺點(diǎn):不兼容ie6,7
<style type="text/css">.div1{ width: 100px; height: 100px; border: 1px solid #000000;} .div2{ width:40px ; height: 40px; background-color: green;}.div11{position: relative;}.div22{position: absolute;margin:auto; top: 0;left: 0;right: 0;bottom: 0;}</style><div class="div1 div11"><div class="div2 div22"></div></div>4.table-cell+vertical-align:middle+margin:auto
<style>.div1{width: 100px;height:100px;border: 1px solid #000;display: table-cell;vertical-align: middle;}.div2{width:50px;height:50px;background: yellow;margin: auto} </style> <div class="div1"><div class="div2"></div> </div>5.flex
缺點(diǎn):不支持IE
<style>.div1{width: 100px;height:100px;border: 1px solid #000;display: flex;align-items: center;jusstify-content: center;}.div2{width:50px;height:50px;background: yellow;} </style> <div class="div1"><div class="div2"></div> </div>6.position+transform
<style>.div1{width: 100px;height:100px;border: 1px solid #000;position: relative;}.div2{width: 80px;height: 80px;background: yellow;position: absolute;top: 50%;left: 50%;transform: translate(-50%,-50%);} </style> <div class="div1"><div class="div2"></div> </div>總結(jié)
以上是生活随笔為你收集整理的div+css盒子居中的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: js中的几种跨域方法
- 下一篇: 谈谈对闭包的理解