星空网 > 软件开发 > 网页设计

DIV内容垂直居中

css垂直居中属性设置vertical-align: middle对div不起作用,例如:

 1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Commpatible" content="IE=edge"> 6 <title>DIV垂直居中对齐</title> 7 <style type="text/css"> 8 * { 9   margin: 0;10   padding: 0;11 }12 13 html, body {14   width: 100%;15   height: 100%;16 }17 18 body {text-align: center; vertical-align: middle;}19 .outer {20   width: 400px;21   height: 120px;22   position: relative;23   left: 20px;24   top: 20px;25   text-align: center;26   vertical-align: middle;27   border: 1px dashed blue;28 }29 30 .button {31   width: 200px;32   height: 40px;33 }34 </style>35 </head>36 <body>37   <div class='outer'>38     <button class='button'>在DIV中垂直居中</button>39   </div>40 </body>41 </html>

运行后按钮没有在DIV中垂直居中:

DIV内容垂直居中

解决思路:如果div和按钮的宽高都确定为具体像素值,可以直接设定按钮的css属性:position:relative; top为(div.height - button.height)/2,left为(div.width-button.height)/2;否则给按钮添加一个div父元素,宽高和按钮相 同,position设定为relative,top和left都为50%(即左上角位置设定在外层div的中心),再将按钮左上角位置坐标设定为父元素 div宽高(也等于按钮自身宽高)的-50%

详细代码如下:

 1 <!DOCTYPE html> 2 <html lang="zh-CN"> 3 <head> 4 <meta charset="utf-8"> 5 <meta http-equiv="X-UA-Commpatible" content="IE=edge"> 6 <title>DIV垂直居中对齐</title> 7 <style type="text/css"> 8 * { 9   margin: 0;10   padding: 0;11 }12 13 html, body {14   width: 100%;15   height: 100%;16 }17 18 body {text-align: center; vertical-align: middle;}19 .outer {20   width: 400px;/* 或者为百分比 */21   height: 120px;22   position: relative;23   left: 20px;24   top: 20px;25   border: 1px dashed blue;26 }27 28 .inner {29   width: 200px;30   height: 40px;31   position: relative;32   position: relative;33   top: 50%;34   left: 50%;35 }36 37 .button {38   width: 200px;39   height: 40px;40   position: relative;41   top: -50%;42   left: -50%;43 }44 </style>45 </head>46 <body>47   <div class='outer'>48     <div class='inner'>49       <button class='button'>在DIV中垂直居中</button>50     </div>51   </div>52 </body>53 </html>

再次运行后,div中按钮上下居中显示

DIV内容垂直居中

END




原标题:DIV内容垂直居中

关键词:div

div
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

胤元电子:https://www.goluckyvip.com/tag/47878.html
英宝通:https://www.goluckyvip.com/tag/47879.html
广告设置技巧:https://www.goluckyvip.com/tag/4788.html
英超海淘:https://www.goluckyvip.com/tag/47880.html
英驰 imc :https://www.goluckyvip.com/tag/47881.html
英创国际咨询:https://www.goluckyvip.com/tag/47882.html
跨境支付百科——巴西支付篇:https://www.kjdsnews.com/a/1836648.html
大福地快捷酒店预订 大福酒店怎么走:https://www.vstour.cn/a/365187.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流