CSS实现DIV居中的三种方法

来源:互联网转载和整理 发布时间:2025-08-17

css div居中

下面给大家分享p居中的实现代码,具体代码如下所示:

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; height: 40px; background-color: green;}  </style>  <p class="p1"><p class="p2"></p>  </p> </body></html>

如上的两个p,实现p2在p1里面是居中显示

一、方法一

利用margin,p1的宽减去p2的宽就是p2margin-left的数值:(100-40)/2=30

p1的高减去p2的高就是p2margin-top的数值:(100-40)/2=30

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; height: 40px; background-color: green;}.p22{  margin-left: 30px;margin-top: 30px;}  </style>  <p class="p1"><p class="p2 p22"></p>  </p> </body></html>
二、方法二

利用css的 position属性,把p2相对于p1的top、left都设置为50%,然后再用margin-top设置为p2的高度的负一半拉回来,用marg-left设置为宽度的负一半拉回来,css如下设置

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; height: 40px; background-color: green;}.p11{  position: relative;}.p22{  position: absolute;top:50%;left: 50%;margin-top: -20px;margin-left: -20px;}  </style>  <p class="p1 p11"><p class="p2 p22"></p>  </p> </body></html>
三、方法三

还是用css的position属性,如下的html

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; height: 40px; background-color: green;}.p11{  position: relative;}.p22{  position: absolute;margin:auto; top: 0;left: 0;right: 0;bottom: 0;}  </style>  <p class="p1 p11"><p class="p2 p22"></p>  </p> </body></html>
四、方法四

利用css3的新增属性table-cell

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; height: 40px; background-color: green;}.p11{  display: table-cell;vertical-align: middle;}.p22{  margin: auto;}  </style>  <p class="p1 p11"><p class="p2 p22"></p>  </p> </body></html>

这个方法还有一个好处就是,p2的高度可以不固定,如下

<!DOCTYPE html><html> <head>  <meta charset="UTF-8">  <title>demo</title> </head> <body>  <style type="text/css">.p1{  width: 100px; height: 100px; border: 1px solid #000000;} .p2{ width:40px ; background-color: green;}.p11{  display: table-cell;vertical-align: middle;}.p22{  margin: auto;}  </style>  <p class="p1 p11"><p class="p2 p22"> p居中方法</p>  </p> </body></html>
总结

热门标签