使用CSS创建固定左侧容器实现垂直布局:技能列表与主内容区实践
在网页布局开发中,固定侧边栏配合主内容区的经典结构非常常见,比如后台管理系统的导航栏、个人简历的技能列表区等场景都会用到。本文将通过一个实际案例,演示如何使用CSS实现左侧固定容器、右侧自适应主内容区的垂直布局效果,完整实现技能列表与主内容区的页面结构。
布局核心思路
要实现左侧固定、右侧自适应的布局,核心思路可以拆解为三个步骤:
- 先给父容器设置相对定位,作为两个子容器的定位参考
- 左侧技能列表容器设置固定宽度和绝对定位,始终固定在左侧区域
- 右侧主内容区设置左外边距,数值等于左侧容器的宽度,让内容自动填充剩余空间
完整HTML结构
首先我们先搭建页面的基础HTML结构,包含外层的布局容器、左侧技能列表区和右侧主内容区三个部分:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>固定左侧技能列表布局示例</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- 外层布局容器 -->
<div class="layout-container">
<!-- 左侧固定技能列表区 -->
<div class="skill-sidebar">
<h3>我的技能列表</h3>
<ul class="skill-list">
<li>HTML/CSS 基础开发</li>
<li>JavaScript 交互实现</li>
<li>Vue 框架应用</li>
<li>Node.js 后端开发</li>
<li>MySQL 数据库操作</li>
</ul>
</div>
<!-- 右侧主内容区 -->
<div class="main-content">
<h2>项目经历</h2>
<div class="content-section">
<h3>电商后台管理系统</h3>
<p>负责系统前端页面开发,使用Vue框架实现商品管理、订单管理、用户管理等核心模块,完成前后端数据交互与页面逻辑开发。</p>
</div>
<div class="content-section">
<h3>个人博客平台</h3>
<p>从零搭建个人博客系统,后端使用Node.js+Express开发接口,前端使用原生JavaScript实现页面交互,支持文章发布、分类管理、评论功能。</p>
</div>
<div class="content-section">
<h3>企业官网重构</h3>
<p>对原有企业官网进行响应式重构,适配PC端、平板、手机等多终端设备,优化页面加载速度,提升用户访问体验。</p>
</div>
</div>
</div>
</body>
</html>CSS样式实现
接下来编写对应的CSS样式,实现左侧固定、右侧自适应的布局效果,同时添加基础的样式美化:
/* 重置默认边距,避免浏览器样式差异 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Microsoft YaHei", sans-serif;
line-height: 1.6;
color: #333;
background-color: #f5f5f5;
}
/* 外层布局容器,设置相对定位作为参考 */
.layout-container {
position: relative;
max-width: 1200px;
margin: 20px auto;
min-height: 100vh;
background-color: #fff;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
/* 左侧固定技能列表区 */
.skill-sidebar {
position: absolute;
left: 0;
top: 0;
width: 240px;
height: 100%;
padding: 20px;
background-color: #2c3e50;
color: #fff;
}
.skill-sidebar h3 {
font-size: 18px;
margin-bottom: 15px;
padding-bottom: 10px;
border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}
.skill-list {
list-style: none;
}
.skill-list li {
padding: 8px 0;
border-bottom: 1px dashed rgba(255, 255, 255, 0.1);
font-size: 14px;
}
/* 右侧主内容区,左外边距等于左侧容器宽度 */
.main-content {
margin-left: 240px;
padding: 30px;
}
.main-content h2 {
font-size: 22px;
margin-bottom: 20px;
color: #2c3e50;
}
.content-section {
margin-bottom: 25px;
padding-bottom: 20px;
border-bottom: 1px solid #eee;
}
.content-section h3 {
font-size: 18px;
margin-bottom: 10px;
color: #3498db;
}
.content-section p {
font-size: 14px;
color: #666;
text-indent: 2em;
}效果说明与扩展
上面的代码运行后,会看到左侧240px宽的深蓝色技能列表区始终固定在页面左侧,右侧主内容区会自动填充剩余的空间,当主内容区内容超过一屏高度时,页面会正常滚动,而左侧技能列表会始终保持在可视区域左侧。如果需要左侧容器也跟随滚动,只需要把.skill-sidebar的定位改成固定定位position: fixed,同时调整.layout-container的样式即可。
这种布局方式的兼容性很好,不需要依赖Flex或者Grid等较新的CSS特性,在老版本浏览器中也能正常展示。如果需要在移动端适配,可以配合媒体查询,在小屏幕下把左侧容器改成顶部导航或者隐藏式侧边栏,提升移动端的访问体验。