目录
[1️⃣ 元素水平布局公式](#1️⃣ 元素水平布局公式)
[2️⃣ 元素居中方案](#2️⃣ 元素居中方案)
[四、label 标签应用](#四、label 标签应用)
[五、CSS 选项卡实现](#五、CSS 选项卡实现)
[六、Swiper 轮播图配置](#六、Swiper 轮播图配置)
一、元素居中与定位规则
1️⃣ 元素水平布局公式
水平布局公式:
left + margin-left + border-left + padding-left + width + padding-right + border-right + margin-right + right = 父级宽度
开启定位(position)后,水平方向布局等式会加入 left 和 right 两个值。
过度约束处理规则:
1️⃣ 如果9个值中没有 auto,则自动调整 right 使等式成立
2️⃣ 如果有 auto,则自动调整 auto 的值
可设为 auto 的属性:margin、width、left、right
常见情况:
-
固定三个值,某个设为 auto 时,会调整该 auto 值
-
当 width、left、right 都为 0 时,margin 会均分左右
多 auto 情况:
-
margin 和 width 为 auto
-
margin 和 left/right 为 auto
-
width 和 left/right 为 auto
-
left 和 right 都为 auto
总结:
1、优先级:right > left > width > margin
2、绝对定位下实现水平垂直居中:
设置四边偏移量为相同固定值,margin 为 auto
2️⃣ 元素居中方案
实现水平垂直居中的方法:
1、绝对定位 + 四边偏移量相同 + margin:auto
2、绝对定位 + left:50%; top:50%; 用 margin 退回自身一半
3、绝对定位 + left:50%; top:50%; 用 transform 平移退回一半
4、父元素 display:table-cell; 子元素 inline-block; 结合 vertical-align 和 text-align
5、父元素使用 Flex,justify-content: center; align-items: center;
css
/* Flex 实现示例 */
.box1 {
display: flex;
justify-content: center;
align-items: center;
}
二、层级(z-index)规则
定位元素层级相同时,下方的元素会覆盖上方的。
通过 z-index 设置层级:
✅ 规则:
-
取值为正整数,数值越大优先级越高
-
未开启定位的元素不能使用 z-index
-
父元素层级再高也不会覆盖子元素(层叠上下文独立)
css
.box4 {
position: relative;
z-index: 999; /* 高层级 */
}
.box5 {
position: relative;
z-index: 0; /* 低层级 */
}
三、透明度设置方案对比
设置透明度的方式:
-
rgba(255,165,0,0)
-
transparent
-
opacity:0
主要区别:
1、rgba/transparent 是属性值,必须跟在具体属性后
opacity 是独立属性
2、rgba/transparent 不影响子元素
opacity 会继承影响子元素
css
.box1 {
background-color: rgba(255,165,0,0.5);
/* 或 */
background-color: transparent;
/* 或 */
opacity: 0.5;
}
| 属性 | 继承性 | 影响范围 |
|---|---|---|
opacity |
是 | 整个元素及子元素 |
rgba() |
否 | 仅背景 |
transparent |
否 | 完全透明背景 |
四、label 标签应用
<label> 作用:
-
提升表单控件的可用性
-
点击标签文字可聚焦关联的表单元素
用法:
- for 属性值需与目标输入框的 id 一致
html
<label for="username">用户名:</label>
<input type="text" id="username" />
五、CSS 选项卡实现
css
/* 选中单选框时修改对应 label 样式 */
input:checked + label {
background-color: blueviolet;
}
/* 显示对应内容块 */
input:checked ~ .box1 {
display: block;
}
实现原理:
- 使用 radio 实现单选逻辑
- 通过 :checked 状态触发样式变化
- 使用相邻(+)或普通(~)兄弟选择器控制内容显示
六、Swiper 轮播图配置
基础结构:
.swiper
.swiper-wrapper
.swiper-slide
.swiper-pagination
.swiper-button-prev/next
css
.swiper {
width: 600px;
height: 300px;
border: 10px solid red;
}
.swiper-button-next,
.swiper-button-prev {
color: #000;
background-color: red;
}
js
var mySwiper = new Swiper(".swiper", {
loop: true,
autoplay: {
delay: 3000,
disableOnInteraction: true,
},
pagination: {
el: ".swiper-pagination",
clickable: true,
},
navigation: {
nextEl: ".swiper-button-next",
prevEl: ".swiper-button-prev",
},
});