50+ CSS 常用代码合集 - 工作必备全面指南

更新时间:2024-04-26 16:02:40   人气:8526
CSS,即层叠样式表(Cascading Style Sheets),是构建网页视觉表现的核心技术之一。以下是一份精心挑选的超过 50 条 CSS 基础及进阶常用代码片段集合,堪称 web 开发者工作中的“瑞士军刀”。这些实用且高效的代码段将助您提升开发效率,并对页面布局和样式的控制达到得心应手的程度。

1. **选择器与注释**
css

/* 全局通用元素 */
* {
margin: 0;
padding: 0;
}

<!-- 类选择器 -->
.center-text {
text-align: center;
}

<!-- ID 选择器 -->
#header {
background-color: #f8f9fa;
}

<!-- 属性选择器 -->
[target="_blank"]{
color:red ;
}


2. **字体设置**:
css

body {
font-family: Arial, sans-serif;
line-height: 1.6em;
}

h1 {
font-size: 3rem;
font-weight: bold;
}


3. **颜色、背景以及边框:**
css

p {
color: rgba(0,0,0,.7);
background-color: lightgray;
border-radius: 4px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

button:focus {
outline:none;
border: 1px solid blue;
}


4. **定位属性**: 使用 `position` 可以进行绝对、相对等位置设定。
css

.fixed-header {
position: fixed;
top: 0;
width: 100%;
}

.absolute-element {
position:absolute;
bottom: 0;
right: 0;
}


5. **响应式设计**(使用媒体查询):
css

@media screen and (max-width: 600px){
div.container {
flex-direction: column-reverse;
}

img.responsive-image {
max-width: 100%; height:auto;
}
}


6. **动画效果**:
css

.box:hover {
transform: scale(1.1);
transition: all ease-in-out 0.3s;
}

@keyframes fadeInOut {
from {opacity: 0;}
to { opacity: 1;}
}

以上只是冰山一角,在实际项目中,熟练掌握并灵活运用这五十多条基础到高级的 CSS 片段能显著提高您的工作效率。无论是处理文本格式化、创建复杂的布局结构还是实现动态交互特效,这份合集都将为您提供强大的技术支持。在日常工作中不断实践积累,逐步打造高效精准的专业级前端编码能力。同时,请时刻关注最新 W3C 标准和技术趋势更新,确保所使用的语法符合现代浏览器的最佳兼容性和性能要求。