Using relative URL in CSS file, what location is it relative to?

前端 未结 8 2283
名媛妹妹
名媛妹妹 2020-11-22 03:29

When defining something like a background image URL in a CSS file, when using a relative URL, where is it relative to? For example:

Suppose the file /styleshe

相关标签:
8条回答
  • 2020-11-22 03:50

    For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

    (Anything else would be broken, IMNSHO)

    0 讨论(0)
  • 2020-11-22 03:54

    This worked for me. adding two dots and slash.

    body{
        background: url(../images/yourimage.png);
    }
    
    0 讨论(0)
  • 2020-11-22 03:57

    In order to create modular style sheets that are not dependent on the absolute location of a resource, authors may use relative URIs. Relative URIs (as defined in [RFC3986]) are resolved to full URIs using a base URI. RFC 3986, section 5, defines the normative algorithm for this process. For CSS style sheets, the base URI is that of the style sheet, not that of the source document.

    For example, suppose the following rule:

    body { background: url("yellow") }
    

    is located in a style sheet designated by the URI:

    http://www.example.org/style/basic.css
    

    The background of the source document's BODY will be tiled with whatever image is described by the resource designated by the URI

    http://www.example.org/style/yellow
    

    User agents may vary in how they handle invalid URIs or URIs that designate unavailable or inapplicable resources.

    Taken from the CSS 2.1 spec.

    0 讨论(0)
  • 2020-11-22 03:58

    It's relative to the stylesheet, but I'd recommend making the URLs relative to your URL:

    div#header { 
      background-image: url(/images/header-background.jpg);
    }
    

    That way, you can move your files around without needing to refactor them in the future.

    0 讨论(0)
  • 2020-11-22 04:01

    It's relative to the CSS file.

    0 讨论(0)
  • 2020-11-22 04:07

    Try using:

    body {
      background-attachment: fixed;
      background-image: url(./Images/bg4.jpg);
    }
    

    Images being folder holding the picture that you want to post.

    0 讨论(0)
提交回复
热议问题