HTML-CSS小知识——background使用的小细节

HTML-CSS小知识——background使用的小细节

background-size中的contain和over

  1. contain为放大背景图片,一直到有一条边接触到边框
    contain效果
  2. over为放大背景图片,先有一条边接触到边框后(这时就是contain),然后继续放大,一直到另一条边接触到边框
    over效果

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>

分析

  1. 情况一:先background-size后background,都是使用类选择器,优先级一样
		div .one{
            float: left;
            background-size: contain;
        }
        div .one{
            width: 190px;
            height: 90px;
            background: url(./sky.jpg) no-repeat center;
        } 
contain没有生效

情况一结果

  1. 情况二:先background-size后background,前面使用类选择器,后面使用标签选择器。优先级:类选择器 > 标签选择器
        div .one{
            float: left;
            background-size: contain;
        }

        div a{
            width: 190px;
            height: 90px;
            background: url(./sky.jpg) no-repeat center;
        }
contain生效

情况二

  1. 情况三:先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生效

情况三

总结

  1. 使用background时直接在后面写上background-size,这样可以避免是否生效的问题。
  2. 优先级:a:first-child > .one > a
        div .one{
            float: left;
            width: 190px;
            height: 90px;
            background: url(./sky.jpg) no-repeat center;
            background-size: contain;
        }

此文章如有不足之处,希望大家在评论区一起交流哦!谢谢大家!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值