水平+垂直 居中
方案一
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>水平居中和垂直居中,并且父容器的宽度高度都是未知的,里面的子容器大小也是不一定的</title> <style type="text/css"> .parent{ background: #bebebe; height: 300px; width: 700px; /* 水平居中*/ text-align: center; /* 垂直居中*/ display: table-cell; vertical-align: middle; } .child{ background: #404040; height: 50px; width: 50px; color:white; /* 水平居中 */ display: inline-block; } </style> </head> <body> <!-- 这个方案的优点: 1。兼容性比较高。 --> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
方案二
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>水平居中和垂直居中 absolute_transform</title> <style type="text/css"> .parent{ background: #bebebe; height: 400px; width: 600px; position: relative; } .child{ background: #404040; height: 50px; color: white; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="parent"> <div class="child">DEMO</div> </div> </body> </html>
方案三
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>水平居中和垂直居中flex_justify-content_align-items</title> <style type="text/css"> .parent{ background: #bebebe; height: 400px; width: 600px; display: flex; justify-content: center; align-items: center; } .child{ background: #404040; color: white; } </style> </head> <body> <div class="parent"> <div class="child"><H1>DEMO</H1></div> </div> </body> <!-- 缺点: 兼容性是个问题。 --> </html>
开始做,坚持做,重复做
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步