网页制作css排版
CSS 排版基础
使用 display 属性控制元素布局方式,常见值包括 block(块级元素)、inline(行内元素)、inline-block(行内块级元素)和 flex(弹性布局)。块级元素独占一行,行内元素按内容宽度排列。
.box {
display: block; /* 默认值可省略 */
}
盒模型与边距
盒模型由 content、padding、border 和 margin 组成。通过 box-sizing 可切换计算方式:
content-box(默认):宽度仅含内容border-box:宽度包含内边距和边框
.item {
padding: 10px;
border: 1px solid #ddd;
margin: 20px;
box-sizing: border-box;
}
浮动与清除浮动
float 使元素脱离文档流,常用于图文混排。需用 clear 或清除浮动技巧避免布局塌陷:
.floated {
float: left;
width: 30%;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
定位方式
position 提供多种定位模式:

static:默认文档流relative:相对自身原位置偏移absolute:相对最近非static父元素定位fixed:相对视口固定定位sticky:滚动时粘性定位
.header {
position: fixed;
top: 0;
z-index: 100;
}
Flex 弹性布局
通过 display: flex 创建弹性容器,常用属性:
flex-direction:主轴方向(row/column)justify-content:主轴对齐方式align-items:交叉轴对齐方式flex-wrap:是否换行
.container {
display: flex;
justify-content: space-between;
}
.item {
flex: 1; /* 等分剩余空间 */
}
Grid 网格布局
display: grid 创建网格容器,通过 grid-template-columns 和 grid-template-rows 定义行列:
.grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 10px;
}
.grid-item {
grid-column: span 2; /* 跨两列 */
}
响应式设计
使用媒体查询(@media)适配不同设备:

@media (max-width: 768px) {
.menu {
flex-direction: column;
}
.grid {
grid-template-columns: 1fr;
}
}
常见布局实现
圣杯布局(三栏自适应):
.container {
display: flex;
}
.main {
flex: 1;
}
.sidebar {
width: 200px;
}
垂直居中:
.center-box {
display: flex;
align-items: center;
justify-content: center;
}
排版优化技巧
使用 line-height 控制行间距,letter-spacing 调整字间距,text-align 设置文本对齐:
.article {
line-height: 1.6;
text-align: justify;
hyphens: auto; /* 自动连字符 */
}






