知道元素的宽高

1.absoult +magin auto

  1. .parent{
  2. /*父元素为除了static以外的定位方式*/
  3. position: relative;
  4. width: 500px;
  5. height: 500px;
  6. border: 1px solid red;
  7. }
  8. .child{
  9. /*子元素为绝对定位*/
  10. position: absolute;
  11. width: 200px;
  12. height: 200px;
  13. /*top、bottom、left和right 均设置为0*/
  14. top: 0;
  15. bottom: 0;
  16. left: 0;
  17. right: 0;
  18. /*margin设置为auto*/
  19. margin:auto;
  20. border: 1px solid green;
  21. }

2.absoult +负magin

  1. .parent{
  2. position: relative;
  3. width: 500px;
  4. height: 500px;
  5. border: 1px solid red;
  6. }
  7. .child{
  8. position: absolute;
  9. width: 200px;
  10. height: 200px;
  11. top: 0;
  12. left: 0;
  13. margin-left: -100px;
  14. margin-top: -100px;
  15. border: 1px solid green;
  16. }

3、.absoult + calc

  1. .parent{
  2. position: relative;
  3. width: 500px;
  4. height: 500px;
  5. border: 1px solid red;
  6. }
  7. .child{
  8. position: absolute;
  9. width: 200px;
  10. height: 200px;
  11. top: calc(50% - 100px);
  12. left: calc(50% - 100px);
  13. border: 1px solid green;
  14. }

不知道元素的宽高

1.webkit-box

  1. //对父级元素设置
  2. position: relative;
  3. display: -webkit-box;
  4. -webkit-box-align: center;
  5. -webkit-box-pack: center;

2.css —tabe

  1. .parent {
  2. width: 500px;
  3. height: 500px;
  4. border: 1px solid red;
  5. display: table-cell;
  6. vertical-align: middle; //实现垂直居中
  7. text-align: center;
  8. }
  9. .child {
  10. display:inline-block;
  11. }

3.flex

  1. .parent{
  2. display:flex;
  3. justify-content:center;
  4. align-items:center;
  5. }

4.absolute+transform

  1. <div class="parent">
  2. <div class="child">Demo</div>
  3. </div>
  4. <style>
  5. .parent {
  6. position: relative;
  7. }
  8. .child {
  9. position: absoult;
  10. left: 50%;
  11. top: 50%;
  12. transform: translate(-50%, -50%); //偏移自身的宽和高的-50%
  13. }
  14. </style>