您的位置:

背景图像大小的完整控制——background-size

一、初探background-size

在CSS中,我们常常需要用到背景图像。但是有时候我们想要图片大小不只是填充整个背景,而是按照一定比例或大小放置,怎么办呢?这时候,我们就需要用到background-size属性。

background-size属性用来控制背景图像的大小。默认值为auto,即将背景图片按照其原有大小展示。我们可以利用background-size实现许多有意思的效果。具体如下:

二、绝对大小控制

如果我们希望背景图片的大小精确到指定的尺寸,可以使用固定的像素或长度单位。

    background-size: 200px 300px;  /*将宽度设置为200px,高度设置为300px*/
    background-size: 50% 80%;      /*将宽度设置为父元素宽度的50%,高度设置为父元素高度的80%*/

注意,如果我们的背景图片比指定的大小小,则会在其周围填充透明区域以达到指定的大小。另外,如果我们只设置了一个值,则该值将被视为宽度,而高度会按比例自动调整。

三、相对大小控制

如果我们希望背景图片相对于其自身大小进行缩放,可以使用百分比。

    background-size: contain;      /*将背景图片缩放至刚好完全展示出(宽度或高度都可能会留有空白区域)*/
    background-size: cover;        /*将背景图片缩放至刚好铺满(宽度或高度可能会超出)*/

contain和cover值在缩放背景图片时非常有用,但有时也可能会因为图片太小或太大而无法满足需求。因此,我们可以结合其他的百分比指定background-size:

    background-size: 50% auto;     /*将背景图片的宽度缩放至父元素的一半,高度自适应*/
    background-size: auto 80%;     /*将背景图片的高度缩放至父元素的80%,宽度自适应*/

四、多重背景及悬浮

在CSS3中,background-size还支持多重背景。这意味着我们可以在同一元素上应用多个背景图片,每个背景图片都有自己的background-size控制。

    background-image: url("bg.png"), url("bg2.png");      /*同时设置两张背景图像*/
    background-size: 50% auto, cover;                      /*第一张背景图像的大小为父元素宽度的50%,高度自适应;第二张背景图像填充完整背景*/

此外,设置background-size的默认值为auto还可以实现背景图片随鼠标悬浮而放大或缩小的效果。我们可以结合:hover伪类和transition属性实现这一效果。

    .bg:hover{
        background-size: 120%;      /*鼠标悬浮时,背景图片放大到120%*/
        transition: 0.5s;           /*过渡效果*/
    }

五、总结

通过以上各种方法,我们可以灵活地控制背景图片的大小,实现多种有趣的效果。

完整示例代码:

<!DOCTYPE html>
<html>
<head>
    <title>背景图像大小的完整控制——background-size</title>
    <style>
        /* 盒模型样式重置 */
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        /* 设置背景图像 */
        .bg{
            background-image: url("bg.png");
            background-size: 50% auto;
            background-position: right center;
            height: 500px;
        }
        /* 鼠标悬浮时放大 */
        .bg:hover{
            background-size: 120%;
            transition: 0.5s;
        }
    </style>
</head>
<body>
    <div class="bg"></div>
</body>
</html>
背景图像大小的完整控制——background-size

2023-05-21
小程序背景图片自适应完整指南

2023-05-17
使用CSS实现背景图像

2023-05-12
when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)?? ---- ---- FTL stack trace ("~" means nesting-related): - Failed at: ${item.id} [in template "article/detail/index.ftl" at line 48, column 106] ---- Java stack trace (for programmers): ---- freemarker.core.InvalidReferenceException: [... Exception message was already printed; see it above ...] at freemarker.core.InvalidReferenceException.getInstance(InvalidReferenceException.java:134) at freemarker.core.EvalUtil.coerceModelToTextualCommon(EvalUtil.java:481) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:401) at freemarker.core.EvalUtil.coerceModelToStringOrMarkup(EvalUtil.java:370) at freemarker.core.DollarVariable.calculateInterpolatedStringOrMarkup(DollarVariable.java:104) at freemarker.core.DollarVariable.accept(DollarVariable.java:63) at freemarker.core.Environment.visit(Environment.java:371) at freemarker.core.IteratorBlock$IterationContext.executedNestedContentForCollOrSeqListing(IteratorBlock.java:321) at freemarker.core.IteratorBlock$IterationContext.executeNestedContent(IteratorBlock.java:271) at freemarker.core.IteratorBlock$IterationContext.accept(IteratorBlock.java:244) at freemarker.core.Environment.visitIteratorBlock(Environment.java:645) at freemarker.core.IteratorBlock.acceptWithResult(IteratorBlock.java:108) at freemarker.core.IteratorBlock.accept(IteratorBlock.java:94) at freemarker.core.Environment.visit(Environment.java:335) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.visit(Environment.java:341) at freemarker.core.Environment.process(Environment.java:314) at freemarker.template.Template.process(Template.java:383) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:332) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:266) at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:220) at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:181) at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:314) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1431) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1167) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1106) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:979) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:903) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:564) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:885) at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:658) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:205) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at com.software.filter.HttpSpiderIdentifyFilter.doFilter(HttpSpiderIdentifyFilter.java:51) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:174) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:149) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:482) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:115) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:340) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:391) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:896) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1744) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) at java.base/java.lang.VirtualThread.run(VirtualThread.java:309)