
CSS 基础总结二
2025年1月10日...大约 4 分钟
CSS 基础总结二
结构伪类选择器
作用:根据元素的结构关系查找元素。
偶数标签 2n
奇数标签 2n+1;2n-1
找到5的倍数的标签 5n
找到第5个以后的标签 n+5
找到第5个以前的标签 -n+5
li:first-child {
background-color: green;
}
li:last-child {
background-color: violet;
}
li:nth-child(5) {
background-color: tomato;
}
li:nth-child(2n) {
background-color: aquamarine;
}
<ul>
<li>li 1</li>
<li>li 2</li>
<li>li 3</li>
<li>li 4</li>
<li>li 5</li>
<li>li 6</li>
<li>li 7</li>
<li>li 8</li>
</ul>
伪元素选择器
作用:创建虚拟元素,用来摆放装饰性的内容。
提示
必须设置 content:""属性,用来设置伪元素的内容,如果没有内容,则引号留空即可。
伪元素默认是行内显示模式。
权重和标签选择器相同。
PxCook 像素大厨
是一款切图设计工具软件。支持 PSD 文件的文字、颜色、距离自动智能识别。
盒子模型
作用:布局网页,摆放盒子和内容。
/* 实线和虚线 */
border: solid/dashed;
/* 居中效果 需要设置width属性*/
margin: 0 auto;
/* 超出隐藏/超出滚动/内容超出时才有垂直滚动 */
overflow: hidden/scroll/auto;
解决办法:
取消自己 margin,父级设置 padding
父级设置 overflow:hidden
父级设置 border-top
/* 盒子外边框塌陷问题解决办法一 */
.father {
width: 300px;
height: 300px;
background-color: brown;
padding-top: 50px;
box-sizing: border-box;
}
.son {
width: 100px;
height: 100px;
background-color: #3fe23f;
}
/* 盒子外边框塌陷问题解决办法二 */
.father {
width: 300px;
height: 300px;
background-color: brown;
overflow: hidden;
}
.son {
width: 100px;
height: 100px;
background-color: #3fe23f;
margin-top: 50px;
}
/* 盒子外边框塌陷问题解决办法三 */
.father {
width: 300px;
height: 300px;
background-color: brown;
border-top: 1px solid #000;
}
.son {
width: 100px;
height: 100px;
background-color: #3fe23f;
margin-top: 50px;
}
<div class="father">
<div class="son">son</div>
</div>
解决办法:给行内元素添加 line-height 可以改变垂直位置。
<style>
span {
margin: 50px;
padding: 20px;
line-height: 100px;
}
</style>
<span>span</span>
<span>span</span>
记忆:从左上角顺时针赋值,没有取值的角与对角取值相同。
清除默认样式
/* 方法一,box-sizing防止盒子被撑大 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 方法二 */
blockquote,
body,
button,
dd,
dl,
dt,
fieldset,
form,
h1,
h2,
h3,
h4,
h5,
h6,
hr,
input,
legend,
li,
ol,
p,
pre,
td,
textare,
th,
ul {
margin: 0;
padding: 0;
}
/* 清除列表前面的装饰符 */
li {
list-style: none;
}