表格布局可以用来实现居中对齐,今天俺就大家一起来学习这个小技巧。
HTML表指的是使用带有原生< Table >标签的表,而CSS表则模拟与HTML表相同的表模型,但具有CSS属性。
我们先来看以下html表单对应的CSS。
table { display: table } tr { display: table-row } thead { display: table-header-group } tbody { display: table-row-group } tfoot { display: table-footer-group } col { display: table-column } colgroup { display: table-column-group } td, th { display: table-cell } caption { display: table-caption }
动态水平垂直居中
代码如下:
<style> body { color: black; background: pink; display: table; width: 100%; height: 100%; } .box { display:table-cell; vertical-align: middle; text-align: center; } </style> <div class="box"> <p>Double Line</p> <p>Double Line</p> </div>
动态水平居中对齐
前端开发中,常见的一种技巧那就是,知道宽度的情况下,使用margin: 0 auto来实现居中对齐,使用display:table;margin: 0 auto;可以在宽度不确定的情况下实现水平居中对齐。
代码如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> *{ margin: 0; padding:0; } .btn{ display: table; padding: 8px 16px; background-color: aqua; border: 1px solid #ddd; color: #fff; margin: 0 auto; } </style> </head> <body> <a class="btn" href="javascript">Dialog</a> </body> </html>