Skip to content

Instantly share code, notes, and snippets.

@ghostcode
Last active March 2, 2023 06:48
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ghostcode/16e05592da16ab088d21 to your computer and use it in GitHub Desktop.
Save ghostcode/16e05592da16ab088d21 to your computer and use it in GitHub Desktop.
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
Copy link

666

@tylerrrkd
Copy link

777

@hasbai
Copy link

hasbai commented Mar 2, 2023

888

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