HTML-CSS小知识——background使用的小细节
background-size中的contain和over
- contain为放大背景图片,一直到有一条边接触到边框
- over为放大背景图片,先有一条边接触到边框后(这时就是contain),然后继续放大,一直到另一条边接触到边框
background-size的位置
在使用时background时会默认产生一个background-size(感觉可以这样理解),同时要注意选择器的优先级的覆盖问题,以后使用时一般将background-size直接放在background后面比较好,避免出现这样的问题。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>background-size</title>
<style>
div{
width: 400px;
height: 100px;
margin: 30px auto;
border: 1px solid red;
}
div .one{
float: left;
background-size: contain;
}
div .one{
width: 190px;
height: 90px;
background: url(./sky.jpg) no-repeat center;
}
</style>
</head>
<body>
<div>
<a href="#" class="one"></a>
</div>
<!-- a:first-child>.class>a,
在使用时background时会默认产生一个background-size(感觉可以这样理解)
以后使用时一般将background-size直接放在background后面比较好
避免出现这样的问题 -->
</body>
</html>
分析
- 情况一:先background-size后background,都是使用类选择器,优先级一样
div .one{
float: left;
background-size: contain;
}
div .one{
width: 190px;
height: 90px;
background: url(./sky.jpg) no-repeat center;
}
contain没有生效
- 情况二:先background-size后background,前面使用类选择器,后面使用标签选择器。优先级:类选择器 > 标签选择器
div .one{
float: left;
background-size: contain;
}
div a{
width: 190px;
height: 90px;
background: url(./sky.jpg) no-repeat center;
}
contain生效
- 情况三:先background-size后background,前面使用后代选择器,后面使用类选择器。优先级:后代选择器 > 类选择器
div a:first-child{
float: left;
background-size: contain;
}
div .one{
width: 190px;
height: 90px;
background: url(./sky.jpg) no-repeat center;
}
contain生效
总结
- 使用background时直接在后面写上background-size,这样可以避免是否生效的问题。
- 优先级:a:first-child > .one > a
div .one{
float: left;
width: 190px;
height: 90px;
background: url(./sky.jpg) no-repeat center;
background-size: contain;
}
此文章如有不足之处,希望大家在评论区一起交流哦!谢谢大家!!!