1、实例演示相邻选择器与兄弟选择器,并分析异同
相邻选择器实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/styles.css"> <title>Document</title> </head> <body> <ul> <li id="bg-blue">1</li> <li class="bg-blue">2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> <li>10</li> </ul> </body> </html>
点击 "运行实例" 按钮查看在线实例
ul {
margin: 0;
padding-left: 0;
border: 1px dashed red;
}
ul li {
width: 30px;
height: 30px;
list-style-type: none;
background-color: wheat;
display: inline-block;
border-radius: 50%;
text-align: center;
line-height: 30px;
box-shadow: 2px 2px 1px #888
}
#bg-blue+* {
background-color: #f00;
}
#bg-blue {
background-color: aqua
}点击 "运行实例" 按钮查看在线实例
运行结果

兄弟选择器实例

相邻选择器选择的是该标签相邻的旁边一个属性,用+表示;
兄弟选择器选择的是该标签后面所以的是属性,用~表示。
2、实例演示:nth-child() 和 :nth-of-type()选择器,并分析异同
:nth-child()
运行结果

:nth-of-type()
运行结果

:nth-child()是从左往右数
:nth-of-type()是随机选择一个数
3、实例演示:padding 对盒子大小的影响与解决方案, 使用宽度分离或box-sizing
宽度分离
实例
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="css/styles.css"> <title>Document</title> </head> <body> <div class="wrap"> <div class="box2"> <img src="https://img.php.cn/upload/course/000/000/001/5d1c6dfc9eb09885.jpg" alt="PHP中文网" width="200"> </div> </div> </body> </html>
点击 "运行实例" 按钮查看在线实例
} */
.wrap {
width: 300px;
}
.box2 {
padding: 50px;
border: 1px solid black;
background-color: lightgreen
}点击 "运行实例" 按钮查看在线实例
运行结果

box-sizing
<div class="box3"> <img src="https://img.php.cn/upload/course/000/000/001/5d1c6dfc9eb09885.jpg" alt="PHP中文网" width="200"> </div>
点击 "运行实例" 按钮查看在线实例
.box3 {
width: 300px;
box-sizing: border-box;
padding: 50px;
background-color: aquamarine;
border: 1px solid black
}点击 "运行实例" 按钮查看在线实例
运行结果

4、实例演示: margin中的同级塌陷, 嵌套传递与自动挤压, 并提出解决方案或应用场景
同级塌陷
.a1 {
width: 100px;
height: 100px;
margin-bottom: 50px;
background-color: brown
}
.a2 {
width: 100px;
height: 100px;
margin-top: 50px;
background-color: green
}点击 "运行实例" 按钮查看在线实例
同级塌陷是垂直方向,谁大以谁为准。
嵌套传递
.a3 {
width: 400px;
height: 400px;
background-color: green
}
.a4 {
width: 100px;
height: 100px;
background-color: brown
}
.a4 {
margin-top: 50px
}点击 "运行实例" 按钮查看在线实例
运行结果

嵌套传递是子元素传递到父元素,子元素嵌套到父元素里面。
自动挤压
.a6 {
width: 100px;
height: 100px;
background-color: brown
}
.a6 {
margin-left: auto
}点击 "运行实例" 按钮查看在线实例
当margin-left: auto时,浏览器会往右边挤压,挤到头为止
当margin-right: auto时,浏览器会往左边挤压,挤到头为止
当margin-left: auto;margin-right: auto同时出现,那么它会居中;
当你想给你想要的往左或往右移动时,最好给它加个值,那么就不会出现自动挤压的情况。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号