css - 在绝对定位的情况下怎么让div居中呢?

查看:113
本文介绍了css - 在绝对定位的情况下怎么让div居中呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

<html>
<head>
    <title></title>
    <style type="text/css">
    #div1{width: 300px;height: 200px;background-color: blue;position: absolute;}
    #div2{width: 50px;height: 50px;background-color: red;margin: 0 auto;position: absolute;bottom:20px;}
    </style>
</head>
<body>
<div id="div1">
    <div id="div2"></div>
</div>
</body>
</html>

解决方案

position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%)

这种方法比较适合自身宽高和容器宽高不明确的情况

补充,自己总结的几种居中方法:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
    .father {
        width: 100px;
        height: 100px;
        border: 1px solid red;
        margin: 20px;
    }

    .child {
        width: 50px;
        height: 50px;
        border: 1px solid red;
        margin-left: auto;
        margin-right: auto;
    }
/*
    方法一:
    对子元素使用margin居中 
    使用场景:
    + 父元素高度固定;
    + 子元素高度固定
    简单粗暴,适用于子元素和父元素的宽高都固定的情况。
*/

    .method1 .child {
        margin-top: 25px;
    }
    /*
    方法二:
    适用于子元素高度和宽度固定,父元素高度不固定
 */

    .method2 {
        position: relative;
    }

    .method2 .child {
        position: absolute;
        top: 50%;
        left: 50%;
        margin-top: -25px;
        margin-left: -25px;
    }
    /*
   方法三:
   子元素和父元素高度不定
   利用transform来调整位置
     */

    .method3 {
        position: relative;
    }

    .method3 .child {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
    /*
    方法四:
    使用flex布局,利用flex-direction属性*/

    .method4 {
        display: flex;
        justify-content: center;
        flex-direction: column;
    }
    /*
    方法五:
    使用flex布局,利用align-items属性*/

    .method5 {
        display: flex;
        display: -webkit-flex;
        align-items: center;
    }
    /*
    方法六:
    使用table-cell布局
     */

    .method6 {
        display: table-cell;
        vertical-align: middle;
        text-align: center;
    }

    .method6 .child {
        vertical-align: middle;
    }
    </style>
</head>

<body>
    <div class="father method1">
        <div class="child"></div>
    </div>
    <div class="father method2">
        <div class="child"></div>
    </div>
    <div class="father method3">
        <div class="child"></div>
    </div>
    <div class="father method4">
        <div class="child"></div>
    </div>
    <div class="father method5">
        <p class="child"></p>
    </div>
      <div class="father method6">
        <p class="child"></p>
    </div>
</body>

</html>

最终效果

这篇关于css - 在绝对定位的情况下怎么让div居中呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆