您可以在 github 仓库中找到这篇文章中的所有代码。

您可以在此处查看垂直中心 - codesandbox 和水平中心的视觉效果。


通过 css 居中


垂直居中

<!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>centering</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    

centering

centering

centering

centering

立即学习前端免费学习笔记(深入)”;

centering

立即学习前端免费学习笔记(深入)”;

centering

centering

</body> </html>
登录后复制
.center-by-absolute-margin {
  position: absolute;
  top: 0;
  bottom: 0;
  margin: auto 0;
}

.center-by-pseudo-class::before {
  content: "";
  display: inline-block;
  height: 100%;
  vertical-align: middle;
}

.center-by-line-height {
  height: 200px;
  line-height: 200;
}

.center-by-table {
  display: table-cell;
  vertical-align: middle;
}

.center-by-flex {
  display: flex;
  align-items: center;
}

.center-by-grid {
  display: grid;
  align-items: center;
}

.center-by-absolute-parent {
  position: relative;
}

.center-by-absolute-child {
  position: absolute;
  top: 50%;
  transform: translatey(-50%);
}

.center-by-calc {
  height: 70px;
  position: relative;
  top: calc(50% - 35px);
}
登录后复制

水平居中

<!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>centering</title>
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    

centering

centering

centering

centering

centering

立即学习前端免费学习笔记(深入)”;

centering

立即学习前端免费学习笔记(深入)”;

centering

centering

</body> </html>
登录后复制
.center-by-fixed-width {
  width: 70px;
  margin: 0 auto;
}

.center-by-text-align {
  text-align: center;
}

.center-by-unfixed-width {
  text-align: center;
}

.center-by-table {
  display: table;
  margin: 0 auto;
}

.center-by-flex {
  display: flex;
  justify-content: center;
}

.center-by-grid {
  display: grid;
  justify-content: center;
}

.center-by-absolute-parent {
  position: relative;
}

.center-by-absolute-child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.center-by-calc {
  width: 70px;
  margin-left: calc(50% - 35px);
}
登录后复制

以上就是居中 - CSS 挑战的详细内容,更多请关注慧达安全导航其它相关文章!

点赞(0)

评论列表 共有 0 条评论

暂无评论
立即
投稿
发表
评论
返回
顶部