css3 - css垂直水平居中?
問(wèn)題描述
如何實(shí)現(xiàn)B在A中,垂直和水平方向都居中?代碼如下:
<!DOCTYPE html><html lang='zh'><head> <meta http-equiv='X-UA-Compatible' content='IE=Edge'> <meta charset='UTF-8'/> <title></title> <style>#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue;} </style></head><body><p id='A'> <p id='B'>哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥哥哥哥哥給哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥給哥哥哥 </p></p></body></html>
問(wèn)題解答
回答1:兩種方法:
第一種:
#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue; /* add */ margin:auto; left:0; right:0; top:0; bottom:0;}
第二種:
#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { position: absolute; max-width: 300px; max-height: 300px; background-color: blue; /* add */ top:50%; left:50%; transform:translate(-50%,-50%);}回答2:
#A {display:table-cell;vertical-align:middle; } #B {/* position:absolute; */margin:0 auto; }
http://jsfiddle.net/7uakz7p1/
回答3:今天剛學(xué)到的一種比較簡(jiǎn)單的方法:父容器設(shè)置display: flex; 要居中的子元素設(shè)置margin: auto;即可。本例中
#A {position: relative;width: 500px;height: 500px;background-color: green;/*add*/display: flex;display: -webkit-flex; }#B {/*position: absolute;*/max-width: 300px;max-height: 300px;background-color: blue;/*add*/margin: auto; }
ps. IE下好像有問(wèn)題...
回答4:#A { position: relative; width: 500px; height: 500px; background-color: green;}#B { width: 50%; height: 50%; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; max-width: 300px; max-height: 300px; background-color: blue;} 回答5:
正好發(fā)現(xiàn)一個(gè)網(wǎng)站,給了好多解決方案 Centering in CSS: A Complete Guide
回答6:http://jsfiddle.net/nbayw7ea/
回答7:http://css-tricks.com/centering-css-complete-guide/
相關(guān)文章:
1. index.php錯(cuò)誤,求指點(diǎn)2. 微信公眾號(hào)在線生成二維碼帶參數(shù)怎么搞?3. 微信開(kāi)放平臺(tái) - android 微信支付后點(diǎn)完成按鈕,后回調(diào)打開(kāi)第三方頁(yè)面,屏幕閃動(dòng),求解決方法4. html5 - H5 video 問(wèn)題5. javascript - umeditor設(shè)置字體,字號(hào)失效,不過(guò)字體顏色,加粗等功能正常6. css - 移動(dòng)端h5播放器問(wèn)題求解決,急急7. PHP單例模式8. javascript - 微信報(bào)redirect_uri參數(shù)錯(cuò)誤9. android - 類(lèi)似微信朋友圈或者QQ空間說(shuō)說(shuō)那種點(diǎn)擊圖片放大,并且有放大縮小手勢(shì),左右滑動(dòng)圖片手勢(shì)效果10. 我在centos容器里安裝docker,也就是在容器里安裝容器,報(bào)錯(cuò)了?
