公共部分, 一共有7种方法

  1. <style>
  2. * {
  3. box-sizing: border-box;
  4. padding: 0;
  5. margin: 0;
  6. }
  7. body {
  8. width: 100%;
  9. height: 100%;
  10. }
  11. /* 待补充 */
  12. </style>
  13. <body>
  14. <div></div>
  15. </body>

定位+位移

  1. div {
  2. position: absolute;
  3. width: 100px;
  4. height: 100px;
  5. top: 50%;
  6. left: 50%;
  7. transform: translate(-50%, -50%);
  8. background-color: red;
  9. margin: auto;
  10. }

定位 + margin=auto方法

  1. div {
  2. position: absolute;
  3. top: 0;
  4. left: 0;
  5. bottom: 0;
  6. right: 0;
  7. width: 100px;
  8. height: 100px;
  9. margin: auto;
  10. background-color: red;
  11. }

定位+margin(top, left一半)

  1. div {
  2. position: absolute;
  3. top: 50%;
  4. left: 50%;
  5. width: 100px;
  6. height: 100px;
  7. margin: -50px 0 0 -50px;
  8. background-color: red;
  9. }

flex方法

  1. body {
  2. width: 100%;
  3. height: 100vh;
  4. /* 这里需要设置页面的高度为100vh,元素会被撑开屏幕高度一致 */
  5. display: flex;
  6. justify-content: center;
  7. align-items: center;
  8. overflow-y: hidden;
  9. }
  10. div {
  11. width: 100px;
  12. height: 100px;
  13. background-color: red;
  14. }

text-center和line-height方法

  1. body {
  2. width: 100%;
  3. height: 100vh;
  4. line-height: 100vh;
  5. text-align: center;
  6. }
  7. div {
  8. display: inline-block;
  9. width: 100px;
  10. height: 100px;
  11. background-color: red;
  12. }

定位+calc方法

  1. div {
  2. position: absolute;
  3. width: 100px;
  4. height: 100px;
  5. top: calc(50% - 50px);
  6. left: calc(50% - 50px);
  7. background-color: red;
  8. margin: auto;
  9. }

grid方法

  • align-items属性控制垂直位置, justify-items属性控制水平位置. 这两个属性的值一致时, 就可以合并写成一个值. 所以, place-items: center; 等同于place-items: center center;
  1. body {
  2. width: 100%;
  3. height: 100vh;
  4. display: grid;
  5. place-items: center;
  6. }
  7. div {
  8. width: 100px;
  9. height: 100px;
  10. background-color: red;
  11. }