以下总结了一些我面试过程中犯的一些错误以及纠正与学习
Q1:要让一个div水平垂直在页面居中怎么实现?
错误示范:我答了一个最无语的,就是给这个div设置为绝对定位,然后 top:0;right:0;left:0;bottom:0;
,然后面试官也是一脸不可置信,我也傻了。最最最基础的知识点,我要乱答。
正确回答:
方法一 :绝对定位:父级是一个相对定位,并且有宽高,也知道子级的宽高,采用top: 50%; left: 50%; transform: translate(-50%,-50%);
<style>
.f{
width: 500px;
height: 500px;
background-color: rgb(225, 231, 235);
position: relative;
}
.son{
width: 100px;
height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
background-color: aqua;
}
</style>
</head>
<body>
<div class="f">
<div class="son"></div>
</div>
</body>
方法二:绝对定位,确定了当前div的宽度,margin值为当前div宽度的一半的负值
.f{
width: 200px;
height: 200px;
position: absolute;
top: 50%;
left: 50%;
margin-top: -100px;
margin-left: -100px;
background-color: aqua;
}
方法三:
绝对定位方法:绝对定位下top left right bottom 都设置0,这里要注意,要用margin:auto,才会生效,我之前就是没有答道margin:auto
<style>
.f{
width: 600px;
height: 600px;
background-color: aqua;
position: relative;
}
.s{
width: 200px;
height: 200px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: bisque ;
margin: auto;
}
</style>
</head>
<body>
<div class="f">
<div class="s"></div>
</div>
</body>
方法四
flex布局方法:当前div的父级添加flex css样式。
代码如下:
<style>
.f{
width: 600px;
height: 600px;
background-color: aqua;
display: flex;
align-items: center;
justify-content: center;
}
.s{
width: 200px;
height: 200px;
background-color: bisque ;
}
</style>
</head>
<body>
<div class="f">
<div class="s"></div>
</div>
</body>
方法五:
table-cell实现水平垂直居中:display:table-cell; vertical-align:middle ; text-align:center
结合使用。垂直居中的如果是div 等块级元素,需设置display: inline-block;
<style>
.f{
width: 600px;
height: 600px;
background-color: aqua;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.s{
width: 200px;
height: 200px;
background-color: bisque ;
display: inline-block;
}
</style>
</head>
<body>
<div class="f">
<div class="s"></div>
</div>
</body>
方法六:
绝对定位:calc( ) 函数动态计算水平居中。calc函数的减号两边一定要有空格
代码如下
<style>
.f{
width: 600px;
height: 600px;
background-color: aqua;
position: relative;
}
.s{
width: 200px;
height: 200px;
background-color: bisque ;
position: absolute;
top: calc((600px - 200px)/2);
left: calc((600px - 200px)/2);
}
</style>
</head>
<body>
<div class="f">
<div class="s"></div>
</div>
</body>
希望这次惨痛经验让我吸取教训,加油Fighting!!!