实现一个元素水平和垂直居中
元素示例:
<div class="container">
<div class="centered-element">居中的内容</div>
</div>
flex布局
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh; /* 设置容器高度为视窗高度,可根据需要调整 */
}
.centered-element {
/* 可以根据需要添加样式 */
}
grid布局
教程:https://www.ruanyifeng.com/blog/2019/03/grid-layout-tutorial.html
.container {
display: grid;
place-items: center;
height: 100vh; /* 设置容器高度为视窗高度,可根据需要调整 */
}
.centered-element {
/* 可以根据需要添加样式 */
}
使用绝对定位
.container {
position: relative;
height: 100vh; /* 设置容器高度为视窗高度,可根据需要调整 */
}
.centered-element {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
/* 可以根据需要添加样式 */
}
实现左右固定,中间自身适应布局
flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
display: flex;
}
.left-sidebar, .right-sidebar {
width: 200px;
height: 100vh;
background-color: #f1f1f1;
}
.main-content {
flex: 1;
padding: 20px;
}
</style>
</head>
<body>
<div class="left-sidebar">Left Sidebar</div>
<div class="main-content">Main Content</div>
<div class="right-sidebar">Right Sidebar</div>
</body>
</html>
grid布局
body {
margin: 0;
display: grid;
grid-template-columns: 200px 1fr 200px;
}
.left-sidebar, .right-sidebar {
height: 100vh;
background-color: #f1f1f1;
}
.main-content {
padding: 20px;
}
左侧固定 右侧自适应
flex布局
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0;
display: flex;
}
.left-sidebar {
width: 200px;
height: 100vh;
background-color: #f1f1f1;
}
.main-content {
flex: 1;
padding: 20px;
}
</style>
</head>
<body>
<div class="left-sidebar">Left Sidebar</div>
<div class="main-content">Main Content</div>
</body>
</html>
grid布局
body {
margin: 0;
display: grid;
grid-template-columns: 200px 1fr;
}
.left-sidebar {
height: 100vh;
background-color: #f1f1f1;
}
.main-content {
padding: 20px;
}