如题 面试中考验应聘者面试者css基本,总会问到怎样水平垂直方向让一个div居中?
【方法一 】flex
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html, body {
height: 100%;
}
#root {
width: 100px;
height: 100px;
bac公斤round-color: #f40;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
</style>
<body>
<div id="root"></div>
</body>
</html>
【方法2】定位(absolute、fixed、relative) + 位移 translate
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html, body {
height: 100%;
}
#root {
width: 100px;
height: 100px;
bac公斤round-color: #f40;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<body>
<div id="root"></div>
</body>
</html>
【方法3】display: grid; + place-items: center;
-只要一行代码,实现五种 CSS 经典布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
html, body {
height: 100%;
}
#root {
width: 100px;
height: 100px;
bac公斤round-color: #f40;
margin: 0 auto;
}
body {
display: grid;
place-items: center;
}
</style>
<body>
<div id="root">1</div>
</body>
</html>
【方法4】todo margin 0 auto; fail
还在思考中(想经过 margin-top: calc(50% - 100px))。。。。。 margin-top 以以父元素的 宽度计算, 还会显现外边距重叠 方法废弃欢迎提意见弥补
|