且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

公司的一个面试题:如何用css让一个容器水平垂直居中?

更新时间:2022-02-27 06:35:23

原文:公司的一个面试题:如何用css让一个容器水平垂直居中?

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>demo</title>
    </head>
    <body>
        <style type="text/css">
            .div1{  width: 100px; height: 100px; border: 1px solid #000000;} 
            .div2{ width:40px ; height: 40px; background-color: green;}
        </style>
        
        <div class="div1">
            <div class="div2">
                
            </div>
        </div>
        
    </body>
</html>

问题:如何让class为div2的内部容器上下左右居中?  

公司的一个面试题:如何用css让一个容器水平垂直居中?

前来面试的朋友大多数回答都不那么正确,笔者在这里给大家做一个详细的介绍

1. 我们可以使用margin来达到这个效果

.div2{ width:40px ; height: 40px; background-color: green; margin-top: 30px; margin-left: 30px;}

 --------我们需要将div2的margin-left、margin-top值设置为父容器宽度的二分之一 减去 自身宽度的二分之一     这里的父容器是div1

它的宽度是100px ; div2的宽度是40px  由此得出  margin-top: 30px; margin-left: 30px; div2也就居中了; 效果如下图

公司的一个面试题:如何用css让一个容器水平垂直居中?

2.利用绝对定位 position:absolute 配合margin的auto属性 来达到居中的效果  我们可以将css修改为 

.div1{  width: 100px; height: 100px; border: 1px solid #000000; position: relative;} 
.div2{ width:40px ; height: 40px; background-color: green; position: absolute; margin: auto; left: 0; top: 0; right: 0; bottom: 0;}

--------将div2设置为相对div1的绝对定位,margin设为四边auto left、top、bottom、right设为0 浏览器会对绝对定位的容器margin:auto自动识别,

最后得到类似于margin:0 auto的效果;

而我们也可以将left、top、bottom、right设为你想要的值 让div2可以在div1中的任意位置,只是定位的原点被margin:auto移动在div2的左上角;例如:

.div2{ width:40px ; height: 40px; background-color: green; position: absolute; margin: auto; left: 0; top: -30px; right: 0; bottom: 0;}

此时div2的位置在垂直居中的-30px的地方;

公司的一个面试题:如何用css让一个容器水平垂直居中?

 总结:在我们的网页中,经常会遇到这样的需求 弹窗的居中,图片的居中,很多童鞋采用js算法动态设置left、top ; 而这一步是没有必要的;

 最后谢谢大家;也感谢大家指正