看父元素是否是块元素,是的话,直接给父元素加个text-align:center
不是的话,把父元素转换成块元素,添加text-align:center;
方法一:
是否有宽度?是的话:margin:auto;
没有的话:默认子元素宽度和父元素一样,然后将子元素转成行内或行内块元素display:inline/inline-block;然后父元素设置text-align:center;
方法二:
(子元素有宽度)
让子元素绝对定位,父元素相对定位,然后子元素走父盒子的一半,往回走子元素盒子宽度的一半
left:50%;
margin-left:-子盒子宽度/2 px;
(子元素没有宽度)
left:50%;
transform:translateX(-50%);
方法三:
给父元素添加:
display:flex;
justify-content:center;
让单行行内元素的line-height=父元素的height就行
给父元素设置display:table-cell; vertical-align:middle;
方法一:
(给了高度)
子绝父相,子元素往下走父盒子一半,再往上走自己盒子的一半
top:50%;
margin-top:-子盒子高度/2 px;
(没有给高度)
top:50%;
transform:translateY(-50%);
方法二:
父元素添加属性display:flex; align-items:center;
定宽高:(2种)
方法一:子绝父相
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>水平垂直居中</title> <style> .dad{ width:400px; height:400px; background-color: goldenrod; position: relative; } .son{ width:200px; height:200px; background-color: green; position:absolute; left:50%; margin-left: -100px; top:50%; margin-top:-100px; } </style> </head> <body> <div class="dad"> <div class="son"></div> </div> </body> </html>方法二:子绝父相
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>水平垂直居中</title> <style> .dad{ width:400px; height:400px; background-color: goldenrod; position: relative; } .son{ width:200px; height:200px; background-color: green; position:absolute; top:0; right:0; bottom:0; left:0; margin:auto; } </style> </head> <body> <div class="dad"> <div class="son"></div> </div> </body> </html>不定宽高(2种)
方法一:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>水平垂直居中</title> <style> .dad{ width:400px; height:400px; background-color: goldenrod; position: relative; } .son{ width:200px; height:200px; background-color: green; position:absolute; left:50%; top:50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="dad"> <div class="son"></div> </div> </body> </html>方法二:
设置父元素为flex定位,为父元素设置justify-content: center; align-items: center;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>水平垂直居中</title> <style> .dad{ width:400px; height:400px; background-color: goldenrod; display: flex; justify-content: center; align-items: center; } .son{ width:200px; height:200px; background-color: green; } </style> </head> <body> <div class="dad"> <div class="son"></div> </div> </body> </html>
