一个盒子如何在另一个盒子中居中

    技术2022-07-10  113

    写页面会碰到不少的居中问题,而有些情况下不能用margin:0 auto来实现水平方向的居中。 如下:

    <style> #outer{ background-color: #00a1ff; width:100px; height:100px; margin:200px auto; text-align:center; position:relative; } #inner{ height:50px; width:50px; background-color:#00ffaa; line-height:50px; position:absolute; margin:0 auto; } </style> <body> <div id="main"> <div id="outer"><div id="inner">居中</div></div> </div> </body>

    运行结果为: 下面来总结一下,让小盒子在大盒子居中的办法:

    第一种方法:

    <style> #outer{ background-color: #00a1ff; width:100px; height:100px; position:relative; margin:200px auto; } #inner{ height:50px; width:50px; background-color:#00ffaa; position:absolute; text-align: center; line-height:50px; top: 0; left: 0; bottom: 0; right: 0; margin: auto; } </style>

    注意:要先采用绝对定位position:absolute,若改为相对定位position:relative;则只会左右居中,不会上下居中。

    第二种方法:左右都为50%的边距,最后要减去自身的宽高的一半,所以margin-left 和 margin-top为负数

    <style> #outer{ background-color: #00a1ff; width:100px; height:100px; position:relative; margin:200px auto; } #inner{ height:50px; width:50px; background-color:#00ffaa; position:absolute; text-align: center; line-height:50px; top:50%; left:50%; margin-top:-25px; margin-left:-25px; } </style>

    注意:需要知道盒子的宽高。

    后续再补充

    Processed: 0.012, SQL: 9