制作css元素
CSS元素的基本结构
CSS元素由选择器和声明块组成。选择器用于指定HTML元素,声明块包含一组属性-值对,用于定义样式。
selector {
property: value;
property: value;
}
常用CSS元素类型
类选择器以点号开头,应用于HTML元素的class属性:
.class-name {
color: blue;
}
ID选择器以井号开头,应用于HTML元素的id属性:
#element-id {
font-size: 16px;
}
元素选择器直接使用HTML标签名:
p {
margin: 10px;
}
复合选择器
后代选择器选择嵌套在另一个元素内的元素:
div p {
line-height: 1.5;
}
子元素选择器选择直接子元素:
ul > li {
list-style: none;
}
伪类和伪元素
伪类用于定义元素的特殊状态:
a:hover {
text-decoration: underline;
}
伪元素用于样式化元素的特定部分:
p::first-letter {
font-size: 150%;
}
盒模型属性
控制元素尺寸和间距:
.box {
width: 200px;
height: 100px;
padding: 20px;
border: 1px solid #000;
margin: 10px;
}
定位方式
静态定位是默认值:
.static {
position: static;
}
相对定位相对于正常位置偏移:
.relative {
position: relative;
top: 10px;
left: 20px;
}
绝对定位相对于最近定位的祖先元素:
.absolute {
position: absolute;
right: 0;
bottom: 0;
}
固定定位相对于视口:
.fixed {
position: fixed;
top: 0;
left: 0;
}
弹性布局
创建弹性容器:
.flex-container {
display: flex;
justify-content: center;
align-items: center;
}
控制弹性项目:
.flex-item {
flex: 1;
order: 2;
}
网格布局
定义网格容器:
.grid-container {
display: grid;
grid-template-columns: 1fr 2fr;
gap: 10px;
}
放置网格项目:
.grid-item {
grid-column: 1 / 3;
grid-row: 1;
}
过渡和动画
创建平滑过渡效果:
.transition {
transition: all 0.3s ease;
}
定义关键帧动画:
@keyframes slide {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
.animate {
animation: slide 2s infinite;
}
响应式设计
媒体查询适配不同屏幕尺寸:
@media (max-width: 768px) {
.responsive {
font-size: 14px;
}
}
变量和自定义属性
定义CSS变量:
:root {
--main-color: #3498db;
}
使用CSS变量:
.element {
color: var(--main-color);
}
现代CSS特性
CSS网格布局示例:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
}
CSS自定义属性与计算:
:root {
--base-size: 16px;
}
.text {
font-size: calc(var(--base-size) * 1.5);
}






