水平垂直居中方法

ゝ一纸荒年。 2023-06-06 10:57 79阅读 0赞
  1. <div id="father">
  2. <div id="son">
  3. </div>
  4. </div>
  1. flex布局

    father {

    1. width: 100px;
    2. height: 100px;
    3. display: flex;
    4. align-items: center;
    5. justify-content: center;
    6. background-color: hotpink;
    7. }
    8. #son {
    9. width: 20px;
    10. height: 20px;
    11. background-color: ivory;
    12. }
  2. 绝对定位

    //1.transform #father {

    1. width: 100px;
    2. height: 100px;
    3. position: relative;
    4. background-color: hotpink;
    5. }
    6. #son {
    7. width: 20px;
    8. height: 20px;
    9. position: absolute;
    10. left: 50%;
    11. top: 50%;
    12. transform: translate(-50%, -50%);
    13. background-color: ivory;
    14. }

    //2.margin负值 #father {

    1. width: 100px;
    2. height: 100px;
    3. position: relative;
    4. background-color: hotpink;
    5. }
    6. #son {
    7. width: 20px;
    8. height: 20px;
    9. position: absolute;
    10. left: 50%;
    11. top: 50%;
    12. margin-left: -10px;
    13. margin-top: -10px;
    14. background-color: ivory;
    15. }

    //3.top left right bottom都为0 margin:auto #father {

    1. width: 100px;
    2. height: 100px;
    3. position: relative;
    4. background-color: hotpink;
    5. }
    6. #son {
    7. width: 20px;
    8. height: 20px;
    9. position: absolute;
    10. left: 0;
    11. top: 0;
    12. right: 0;
    13. bottom: 0;
    14. margin: auto;
    15. background-color: ivory;
    16. }
  3. table-cell


    我居中了哦


    father {

    1. width: 200px;
    2. height: 200px;
    3. display: table-cell;
    4. vertical-align: middle;
    5. text-align: center;
    6. background-color: khaki;
    7. }

4.calc动态计算

  1. #father {
  2. position: relative;
  3. width: 400px;
  4. height: 160px;
  5. background-color: lawngreen;
  6. }
  7. #son {
  8. position: absolute;
  9. width: 200px;
  10. height: 50px;
  11. background-color: khaki;
  12. left: -webkit-calc((400px - 200px)/2);
  13. top: -webkit-calc((160px - 50px)/2);
  14. left: -moz-calc((400px - 200px)/2);
  15. top: -moz-calc((160px - 50px)/2);
  16. left: calc((400px - 200px)/2);

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读

    相关 水平垂直居中

    实现水平垂直居中的方法有很多,在这里我只介绍两种易用且常见的方法,这两种方法对于固定宽高和不定宽高都有效。 1、transform 方案 // html部分

    相关 水平/垂直居中

    一. 水平居中 1.1行内或类行内元素(比如文本和链接) 在块级父容器中让行内元素居中,只需使用 text-align: center;: 这种方法可以

    相关 水平垂直居中

    (1)水平居中: 元素为行内元素,设置父元素text-align:center 如果元素宽度固定,可以设置左右margin为auto 如果元素为绝对定位(或