面试官:元素水平垂直居中,想起来几种方案,你就说几种
我:(我是搞Java的,这是CSS知识吧)好的.
通过以下几种方式实现.
方案一:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: greenyellow;
position: relative;
}
.item {
width: 50px;
height: 50px;
background-color: black;
color: #ffffff;
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px;
margin-left: -25px;
}
</style>
</head>
<body>
<div class="box">
<div class="item">hello world</div>
</div>
</body>
</html>
面试官:嗯,不错,这种方法需要知道父元素宽高,并且子元素的margin值需要人肉计算,假如要让box在body里水平垂直居中呢,有思路么?
我:(您到底问不问Java的知识啊)有,方案二
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 200px;
height: 200px;
background-color: greenyellow;
}
.item {
width: 50px;
height: 50px;
background-color: black;
color: #ffffff;
}
</style>
</head>
<body>
<div class="box">
<div class="item">hello world</div>
</div>
</body>
</html>
嗯,不错,没想到你对前端的基础掌握的还可以,你上面这两种办法都是基于定位来实现的,如果不用定位实现呢?
我:我想想~可以利用行内元素类文字的特性设置line-height解决
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
/*height: 200px;*/
background-color: greenyellow;
text-align: center;
line-height: 200px;
}
.item {
width: 50px;
height: 50px;
background-color: black;
color: #ffffff;
display: inline;
}
</style>
</head>
<body>
<div class="box">
<div class="item">hello world</div>
</div>
</body>
</html>
面试官:嗯,我看你把父元素的高,注释掉了,这是为什么,能解释一下么
我:因为元素的高是被行高撑起来的,而不是高度.
面试官:那如果我不设置行高,元素会有行高么?
我:会,它默认值是normal,此时行高与字体关联,如果你的取值是number,那么它会根据font-size重新计算行高.
面试官:(你小子还有两下子)可以,我看你上一个代码,你觉得有什么瑕疵么?
我:将子元素设置成display:inline转化成行内元素导致宽高失效.
面试官:那你还有别的解决办法么?
我:(我这是面Java还是前端?)有的,可以用flex布局来实现
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
* {
padding: 0;
margin: 0;
}
.box {
width: 200px;
height: 200px;
background-color: greenyellow;
display: flex;
justify-content: center;
align-items: center;
}
.item {
width: 50px;
height: 50px;
background-color: black;
color: #ffffff;
}
</style>
</head>
<body>
<div class="box">
<div class="item">hello world</div>
</div>
</body>
</html>
面试官:不错,基础掌握的还行,Java相关的下回再问,我觉得你大概能值7k.
我:我还值7k?
969

被折叠的 条评论
为什么被折叠?



