如何实现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><div id="A"> <div id="B">哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥 哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥 哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥 哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥 哥哥哥哥给哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥哥给哥哥哥 </div></div></body></html>
解决方案
两种方法:
第一种:
#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%); }