純CSS實現DIV上下左右居中 二維碼
發表時間:2017-07-25 23:51 (1)被居中元素寬高已知只要使得父元素相對定位,子元素絕對定位,子元素的top和left都為50%,margin-top和margin-left分別為寬高的負一半即可。 <!--上下左右居中--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>DIV上下左右居中</title> <style type="text/css"> *{/*實現div的上下左右居中*/ margin: 0; padding: 0; }/*清除格式*/ .div0{ height: 1000px; width: 800px; position: relative;/*父元素相對定位*/ background: #678680; } .div1{ position: absolute;/*子元素絕對定位*/ height: 240px; width: 300px; /*overflow: hidden;*//*可使得多出塊元素的文本隱藏*/ top: 50%; left: 50%; margin-top: -120px;/*高的一半*/ margin-left: -150px;/*寬的一半*/ border: 5px solid #E58B8B; text-align: center; } .div1 p{ font-size: 36px; } </style> </head> <body> <div class="div0"> <div class="div1"> <p>hello world!</p> <p>hello world!</p> </div> </div> </body> </html> (2)被居中元素寬高未知<!--上下左右居中--> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上下左右居中</title> <style type="text/css"> *{/*實現div的上下左右居中*/ margin: 0; padding: 0; }/*清除格式*/ .div0{ height: 500px; width: 500px; position: relative;/*父元素相對定位*/ background: #678680; } .div1{/*被居中元素寬高未知*/ position: absolute;/*子元素絕對定位*/ top: 100px; bottom: 100px; left: 200px; right: 200px;/*設置上下左右撐開以居中*/ background: #E3A5A5; text-align: center; } </style> </head> <body> <div class="div0"> <div class="div1"> </div> </div> </body> </html> |