在前端的界面佈局中有一種這樣的狀況,就是個人塊元素的寬和高我不知道具體的大小是多少,只知道寬和高佔當前屏幕的多少百分比。html
如今這種狀況下有兩個div元素,一個大,一個小,如今我須要讓小的塊元素位於大的塊元素的中心位置前端
以下圖:佈局
下面是實現代碼:spa
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style> .one { background-color: #FF0000; width: 100%; height: 100%; position: absolute; } /*定位上下左右都爲0,這樣四周受力平衡,再給定一個margin,屬性值是auto自適應,這樣就能夠居中了*/ .two { background-color: #2AC845; width: 20rem; height: 20rem; position: absolute; top: 0; right: 0; left: 0; bottom: 0; margin: auto; } </style> </head> <body> <div class="one"> <div class="two"></div> </div> </body> </html>