下面給大家分享div居中的實(shí)現(xiàn)代碼,具體代碼如下所示:
| <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> <style type="text/css"> .div1{ width: 100px; height: 100px; border: 1px solid #000000;} .div2{ width:40px ; height: 40px; background-color: green;} </style> <div class="div1"> <div class="div2"> </div> </div> </body></html> | 

如上的兩個(gè)div,實(shí)現(xiàn)div2在div1里面是居中顯示
一、方法一
利用margin,div1的寬減去div2的寬就是div2margin-left的數(shù)值:(100-40)/2=30
div1的高減去div2的高就是div2margin-top的數(shù)值:(100-40)/2=30
| <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> <style type="text/css"> .div1{ width: 100px; height: 100px; border: 1px solid #000000;} .div2{ width:40px ; height: 40px; background-color: green;} .div22{ margin-left: 30px;margin-top: 30px; } </style> <div class="div1"> <div class="div2 div22"> </div> </div> </body></html> | 

二、方法二
利用css的 position屬性,把div2相對(duì)于div1的top、left都設(shè)置為50%,然后再用margin-top設(shè)置為div2的高度的負(fù)一半拉回來(lái),用marg-left設(shè)置為寬度的負(fù)一半拉回來(lái),css如下設(shè)置
| <!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>demo</title> </head> <body> <style type="text/css"> .div1{ width: 100px; height: 100px; border: 1px solid #000000;} .div2{ width:40px ; height: 40px; background-color: green;} .div11{ position: relative; } .div22{ position: absolute;top:50%;left: 50%;margin-top: -20px;margin-left: -20px; } </style> <div class="div1 div11"> <div class="div2 div22"> </div> </div> </body></html> | 
            
新聞熱點(diǎn)
疑難解答
圖片精選