Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

常见的 css 水平垂直居中的 5 种方法 #126

Open
Popxie opened this issue Sep 3, 2021 · 0 comments
Open

常见的 css 水平垂直居中的 5 种方法 #126

Popxie opened this issue Sep 3, 2021 · 0 comments
Assignees

Comments

@Popxie
Copy link
Owner

Popxie commented Sep 3, 2021

常见的 css 水平垂直居中的 5 种方法

02_常见的css水平垂直居中的5种方法

前言

这两天总是在掘金插件上看到一些关于 css 垂直水平居中的基础文章,刚好很久之前自己也总结了一些,那我也就分享一下自己平常用的方法吧~

12

先看效果

垂直水平居中

代码实践

<div class="parent">
  <div class="children"></div>
</div>
/* 方法一 利用flex 作用在父元素 */
.parent {
  height: 300px;
  background: lightcoral;

  display: flex;
  justify-content: center; // 水平方向
  align-items: center; // 垂直方向
}
/* 方法二 利用定位 作用在子元素 */
.parent {
  height: 300px;
  background: lightblue;

  position: relative;
}
.children {
  height: 200px;
  width: 200px;
  background: green;

  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
/* 方法三 利用flex 作用在子元素 也适用于高度不固定的情况 */
.parent {
  height: 300px;
  background: lightsalmon;

  display: flex; 
}
.children {
  height: 200px;
  width: 200px;
  background: green;

  align-self: center;
  margin: 0 auto;
}
/* 方法四 利用定位 作用在子元素 */
.parent {
  background: lightskyblue;
  height: 300px;

  position: relative;
}
.children {
  width: 200px;
  height: 200px;
  background: green;

  position: absolute;
  top: calc(50% - 100px);
  left: calc(50% - 100px);
}
/* 方法五 定位 作用在子元素 */
.parent {
  background: yellowgreen;
  height: 300px;

  position: relative;
}
.children {
  width: 200px;
  height: 200px;
  background: green;

  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
}
@Popxie Popxie self-assigned this Sep 3, 2021
@Popxie Popxie added the CSS label Sep 3, 2021
@Popxie Popxie closed this as completed Sep 3, 2021
@Popxie Popxie changed the title 4 常见的 css 水平垂直居中的 5 种方法 Sep 8, 2021
@Popxie Popxie reopened this Sep 8, 2021
@Popxie Popxie added the 博文 label Sep 8, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant