div居中显示的三种方式
方法1:固定宽高元素水平垂直居中
通过margin平移元素整体宽度的一半,使元素水平垂直居中。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>固定宽高元素水平垂直居中</title> <style> .parent { height: 140px; position: relative; border: 2px dashed #f69c55; } .child { width: 200px; height: 80px; padding: 10px; position: absolute; top: 50%; left: 50%; margin: -50px 0 0 -110px; background: black; color: #fff; } </style> </head> <body> <div class="parent"> <div class="child">测试文本,测试文本。</div> </div> </body> </html>
效果图:
方法2:未知宽高元素水平垂直居中
利用2D变换,在水平和垂直两个方向都向反向平移宽高的一半,从而使元素水平垂直居中。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>未知宽高元素水平垂直居中</title> <style> .parent { height: 140px; position: relative; border: 2px dashed #f69c55; } .child { padding: 10px; position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #fff; background: black; } </style> </head> <body> <div class="parent"> <div class="child">测试文本,测试文本。</div> </div> </body> </html>
效果图:
方法3:利用flex布局
利用flex布局,其中justify-content 用于设置或检索弹性盒子元素在主轴(横轴)方向上的对齐方式;而align-items属性定义flex子项在flex容器的当前行的侧轴(纵轴)方向上的对齐方式。
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>利用flex布局实现元素水平垂直居中</title> <style> .parent { height: 140px; display: flex; justify-content: center; align-items: center; border: 2px dashed #f69c55; } .child { padding: 20px; background: black; color: #fff; } </style> </head> <body> <div class="parent"> <div class="child">测试文本,测试文本。</div> </div> </body> </html>
效果图:
以上就是div居中显示的三种方式是什么?的详细内容,更多请关注0133技术站其它相关文章!