想要水平居中?
-
内联的元素(文字)?
.center-children { text-align: center;}
-
块级元素?
.center-me { margin: 0 auto;}
-
如果有多个块级元素呢?
.inline-block-center { text-align: center; } .inline-block-center div { display: inline-block; text-align: left; } .flex-center { display: flex; justify-content: center; }
想要垂直居中?
-
内联的元素?
- 如果只有一行的话,可以设置上下内边距为相同的值。
- 如果是多行文本的话,可以模拟表格。
.center-table { display: table; height: 250px; background: white; width: 240px; margin: 20px; } .center-table p { display: table-cell; margin: 0; background: black; color: white; padding: 20px; border: 10px solid white; vertical-align: middle; } .flex-center-vertically { display: flex; justify-content: center; flex-direction: column; height: 400px; } 块级元素? 知道元素高度? .parent { position: relative; } .child { position: absolute; top: 50%; height: 100px; margin-top: -50px; /* account for padding and border if not using box-sizing: border-box; */ }
- 元素高度未知?
.parent { position: relative; } .child { position: absolute; top: 50%; transform: translateY(-50%); }
- flex布局
.parent { display: flex; flex-direction: column; justify-content: center; }
原文地址:
时间: 2024-10-26 03:24:24