面试精心整理,基本都问到了,希望能帮助大家更精确的了解知识点,接下来持续更新中。。。
CSS选择器权重
!Important > 内联样式(1000)> ID选择器(#)(100) > 类选择器/属性选择器/伪类选择器(10) > 元素选择器/伪元素选择器(1) > 关系选择器/通配符选择器
属性选择器是一种在CSS中用于根据元素的属性值选择并应用样式的方法。它允许我们根据元素的属性来精确地选择和定制样式,而不仅仅局限于元素的标签名或类别。
属性选择器可以基于以下条件进行选择:
属性存在与否:使用[attribute]选择器可以选择具有指定属性的所有元素。
css
[required] {
border: 1px solid red;
}
上述示例将选择所有具有required属性的元素,并为它们添加红色边框。
属性值精确匹配:使用[attribute=value]选择器可以选择具有指定属性值的元素。
css
[type="submit"] {
background-color: blue;
color: white;
}
上述示例将选择所有type属性值为submit的元素,并设置其背景颜色为蓝色,文字颜色为白色。
属性值以指定字符串开头:使用[attribute^=value]选择器可以选择属性值以指定字符串开头的元素。
css
[href^="https://"] {
color: green;
}
上述示例将选择所有href属性值以https://开头的链接元素,并将它们的文字颜色设置为绿色。
属性值以指定字符串结尾:使用[attribute$=value]选择器可以选择属性值以指定字符串结尾的元素。
css
[src$=".jpg"] {
border: 2px solid black;
}
上述示例将选择所有src属性值以.jpg结尾的图像元素,并为它们添加黑色边框。
属性值包含指定字符串:使用[attribute*=value]选择器可以选择属性值中包含指定字符串的元素。
css
[data-category*="fruit"] {
font-weight: bold;
}
上述示例将选择所有data-category属性值中包含fruit字符串的元素,并将它们的字体加粗。
清除浮动
- 浮动元素后添加空<div style="clear:both"></div>
<div class="container">
<div class="left"></div>
<div class="right"></div>
<div style="clear:both"></div>
</div>
- 给父元素添加overflow:hidden或者auto样式,触发BFC
<div class="container">
<div class="left"></div>
<div class="right"></div>
</div>
.container{
width: 300px;
background-color: #aaa;
overflow:hidden;
zoom:1; /*IE6*/
}
- 使用伪元素,也是在父元素内容末尾添加一个点并带有clear:both属性的元素实现的
<div class="clearfix">
<div class="left"></div>
<div class="right"></div>
</div>
.clearfix{
zoom: 1; /*IE6*/
}
.clearfix:after{
content: ".";
height: 0;
clear: both;
display: block;
visibility: hidden;
}
水平垂直居中的方法
1.利用绝对定位+transform,设置left:50%,top:50% ,可不定宽高
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
2.利用绝对定位+margin:auto,子元素所有方向都为0,该方法必须有宽高
- 利用绝对定位+margin:负值,left:50%和top:50%,再通过margin-left和margin-top 以子元素自身一半的高度进行负值赋值,必须定宽高
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 200px;
margin-left: -100px;
margin-top: -100px;
}
3.利用display: flex,可不定宽高,justify-content: center; align-items: center;
<style>
.father {
display: flex;
justify-content: center;
align-items: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 100px;
height: 100px;
background: red;
}
</style>
<div class="father">
<div class="son"></div>
</div>
4.display: grid,网格布局,justify-content: center; align-items: center; 定宽高
<style>
.father {
display: grid;
align-items:center;
justify-content: center;
width: 200px;
height: 200px;
background: skyblue;
}
.son {
width: 10px;
height: 10px;
border: 1px solid red
}
</style>
<div class="father">
<div class="son"></div>
</div>
5.父元素display:table-cell布局
vertical-align:middle,text-align:center 子元素display;inline-block 可以让所有行内块级元素水平垂直居中