Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Flex实现水平垂直居中

水平垂直居中是前端的痛,也是前端__永恒__话题,这次记录两个用display:flex实现的方法:

Snipaste_2020-11-02_11-41-33

第一种:

html

<div class="flex">
  <p>内容</p>
</div>

css

.flex{
  display:flex;
  width:600px;
  height:600px;
  background-color:#ff9900;
}

.flex p{
  margin:auto;
  
  /* 修饰作用 */
  background-color: #000000;
  padding:20px;
  color:#fff;
  font-size:40px;
  font-weight:700;
}

https://codepen.io/ghostcode/pen/WNxJdNN

第二种:

html

<div class="flex">
  <p>内容</p>
</div>

css

.flex{
  display:flex;
  align-items:center;
  justify-content:center;
  width:600px;
  height:600px;
  background-color:#333;
}

.flex{
  display:flex;
  align-items:center;
  justify-content:center;
  width:600px;
  height:600px;
  background-color:#ff9900;
}
.flex p{
  /* 修饰作用 */
  background-color: #000000;
  padding:20px;
  color:#fff;
  font-size:40px;
  font-weight:700;
}

https://codepen.io/ghostcode/pen/gOMzoOq

@Joseph-Alice

This comment has been minimized.

Copy link

@Joseph-Alice Joseph-Alice commented Feb 28, 2018

666

@tylerrrkd

This comment has been minimized.

Copy link

@tylerrrkd tylerrrkd commented May 24, 2018

777

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment