一、布局与定位技巧

1. ‌居中元素的终极方案‌

1. /* 水平垂直居中 */
2. .center-box {
3.   display: grid;
4.   place-items: center;
5. }
6. 
7. /* 替代传统flex方案 */
8. .center-flex {
9.   display: flex;
10.   justify-content: center;
11.   align-items: center;
12. }

2. ‌使用gap简化间距控制‌

1. .grid-container {
2.   display: grid;
3.   grid-template-columns: repeat(3, 1fr);
4.   gap: 20px; /* 同时控制行列间距 */
5. }
6. 
7. .flex-container {
8.   display: flex;
9.   gap: 15px; /* 兼容性良好的现代浏览器 */
10. }

3. ‌粘性定位实现悬浮标题‌

1. .sticky-header {
2.   position: sticky;
3.   top: 0;
4.   background: white;
5.   z-index: 100;
6. }

二、样式优化技巧

4. ‌文本溢出省略处理‌

1. .ellipsis {
2.   white-space: nowrap;
3.   overflow: hidden;
4.   text-overflow: ellipsis;
5. }
6. 
7. /* 多行文本省略(需结合行高) */
8. .multi-line-ellipsis {
9.   display: -webkit-box;
10.   -webkit-line-clamp: 3;
11.   -webkit-box-orient: vertical;
12.   overflow: hidden;
13. }

5. ‌自定义滚动条样式‌

1. ::-webkit-scrollbar {
2.   width: 8px;
3. }
4. 
5. ::-webkit-scrollbar-track {
6.   background: #f1f1f1; 
7. }
8. 
9. ::-webkit-scrollbar-thumb {
10.   background: #888;
11.   border-radius: 4px;
12. }

最佳实践建议

  1. ‌优先使用Flex/Grid布局‌:避免传统浮动布局
  2. ‌保持选择器简洁‌:避免过度嵌套(建议不超过3层)
  3. ‌使用CSS自定义属性‌:统一管理设计系统
  4. ‌定期检查未使用样式‌:使用PurgeCSS等工具
  5. ‌渐进增强原则‌:先用基础样式,再添加新特性

任性的毛衣
1 声望0 粉丝