基础系列:布局解决方案【水平居中】
思路一inner-block+text-align
- 子div设置display:inner-block; 子div宽度根据内容而改变
- 父div设置text-align:center; 对子div是inner元素起作用
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .child{ display: inline-block; } .parent{ text-align: center; } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
思路二table+margin
- 子div设置display:table; 子div宽度是跟着内容走
- 子div设置margin:0 auto;
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .child{ display: table; margin: 0 auto; } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
思路三绝对定位+transform 兼容性问题
- 设置父div display:relative; 子div设置 display:absolute; 子div的宽度随内容改变
- 往左偏移自身一半
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .parent{ position: relative; } .child{ position: absolute; left: 50%; transform:translateX(-50%); } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
思路四flex+justify-content
- 父div设置display:flex; 这样 宽度 根据内容改变
- 父div的 display:flex; 可以设置 justify-content:center;这样就居中;或者设置子div的 margin:0 auto;
<!DOCTYPE html> <html> <head> <title></title> <style type="text/css"> .parent{ display: flex; justify-content:center; } /*或者 justify-content:center; 去掉 设置 .child{ margin:0 auto;} */ </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>