<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <style type="text/css"> </style> </head> <body> <div class="father"> <div class="son">1111</div> </div> </body> </html>
方法一(使用絕對布局): 這種方式的弊端是:必須要知道這個容器的長寬,因為在子元素中的 margin-top:-100px; margin-left:-100px; 這兩個樣式分別是子元素長、寬的一半。
.father { width: 500px; height: 500px; position: relative; background-color: red; } .son { width: 200px; height: 200px; position: absolute; top: 50%; left: 50%; margin-top: -100px; margin-left: -100px; background-color: black; }
萬能方式二:仍然是絕對布局,讓left和top都是50%,這在水平方向上讓div的最左與屏幕的最左相距50%,垂直方向上一樣,所以再用transform向左(上)平移它自己寬度(高度)的50%,也就達到居中效果了,效果圖和上方相同。//這種方式很好的避免了方式一的弊端,不需要知道自己的長寬,一樣可以定位到中間
.father{ width: 1000px; height: 600px; position: relative; background-color: red; } .son { background-color: #fff; width: 300px; height: 300px; position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
3.萬能方法三(使用彈性布局flex) //這種方式比較通用:這樣給父元素設置了三個樣式display:flex;(彈性布局) justify-content:center;(內容水平居中) align-items:center; (內容垂直居中) 就可以達到水平、垂直居中的效果
.father { width: 500px; height: 500px; display: flex; justify-content: center; align-items: center; background-color: red; } .son { width: 200px; height: 200px; background-color: black; }
4.方法四(使用絕對布局) //使用這種方式的要領是:子絕父相,且子元素要設置以下的樣式position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; 就可以達到居中效果
.father { width: 500px; height: 500px; position: relative; background-color: red; } .son { width: 200px; height: 200px; position: absolute; top: 0; right: 0; bottom: 0; left: 0; margin: auto; background-color: black; }
如果文章對你有幫助,麻煩幫忙點個贊哦!嘿嘿!做一個靠譜的技術博主!