当前位置:   article > 正文

[CSS]中子元素在父元素中居中

[CSS]中子元素在父元素中居中

元素居中

对于当行文字居中,比较简单,设置text-align:center和text-height为盒子高度即可

对于父元素中子元素居中,要实现的话有以下几个方法

方法1:利用定位+margin:auto

  1. <style>
  2.  .father {
  3.    width: 500px;
  4.    height: 300px;
  5.    border: 1px solid #0a3b98;
  6.    position: relative;
  7. }
  8.  .son {
  9.    width: 100px;
  10.    height: 40px;
  11.    background: #f0a238;
  12.    position: absolute;
  13.    top: 0;
  14.    left: 0;
  15.    right: 0;
  16.    bottom: 0;
  17.    margin:auto;
  18. }
  19. </style>
  20. <div class="father">
  21.  <div class="son"></div>
  22. </div>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left,right,bottom为0,并设置margin:auto

方法2:利用定位+margin:负值

  1. <style>
  2. .father {
  3. position: relative;
  4. width: 200px;
  5. height: 200px;
  6. background: skyblue;
  7. }
  8. .son {
  9. position: absolute;
  10. top: 50%;
  11. left: 50%;
  12. margin-left:-50px;
  13. margin-top:-50px;
  14. width: 100px;
  15. height: 100px;
  16. background: red;
  17. }
  18. </style>
  19. <div class="father">
  20. <div class="son"></div>
  21. </div>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left为50%,并设置margin-left和margin-top为盒子大小的一半-50px(这种情况需要知道盒子大小)

方法3:利用定位+transform

  1. <style>
  2. .father {
  3. position: relative;
  4. width: 200px;
  5. height: 200px;
  6. background: skyblue;
  7. }
  8. .son {
  9. position: absolute;
  10. top: 50%;
  11. left: 50%;
  12. transform: translate(-50%,-50%);
  13. width: 100px;
  14. height: 100px;
  15. background: red;
  16. }
  17. </style>
  18. <div class="father">
  19. <div class="son"></div>
  20. </div>

父元素中relative相对定位,子元素absolute绝对定位,并设置top,left为50%,并使用transform移动-50%,transform: translate(-50%,-50%); 此方法不需要知道盒子大小

方法4:利用flex

  1. <style>
  2. .father {
  3. display: flex;
  4. justify-content: center;
  5. align-items: center;
  6. width: 200px;
  7. height: 200px;
  8. background: skyblue;
  9. }
  10. .son {
  11. width: 100px;
  12. height: 100px;
  13. background: red;
  14. }
  15. </style>
  16. <div class="father">
  17. <div class="son"></div>
  18. </div>

使用flex布局,设置justify-content: center; 水平居中 align-items: center;设置垂直居中

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/353492
推荐阅读
相关标签
  

闽ICP备14008679号