DIV内容垂直居中 - MySomeDay
程序员文章站
2022-04-04 19:41:32
...
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和按钮的宽高都确定为具体像素值,可以直接设定按钮的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中按钮上下居中显示
END