Is it possible to set the equivalent of a src attribute of an img tag in CSS?

后端 未结 25 2571
借酒劲吻你
借酒劲吻你 2020-11-22 09:30

Is it possible to set the src attribute value in CSS? At present, what I am doing is:


25条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 09:58

    A collection of possible methods to set images from CSS


    CSS2's :after pseudo-element or the newer syntax ::after from CSS3 along with the content: property:

    First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998
    Latest W3C Recommendation: Selectors Level 3 W3C Recommendation 29 September 2011

    This method appends content just after an element's document tree content.

    Note: some browsers experimentally render the content property directly over some element selectors disregarding even the latest W3C recommendation that defines:

    Applies to: :before and :after pseudo-elements

    CSS2 syntax (forward-compatible):

    .myClass:after {
      content: url("somepicture.jpg");
    }
    

    CSS3 Selector:

    .myClass::after {
      content: url("somepicture.jpg");
    }
    

    Default rendering: Original Size (does not depend on explicit size declaration)

    This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.

    but even at the time of this writing, behaviour with a tag is still not defined and although it can be used in a hacked and non standards compliant way, usage with is not recommended!

    Great candidate method, see conclusions...



    CSS1's background-image: property:

    First W3C Recommendation: Cascading Style Sheets, level 1 17 Dec 1996

    This property sets the background image of an element. When setting a background image, one should also set a background color that will be used when the image is unavailable. When the image is available, it is overlaid on top of the background color.

    This property has been around from the beginning of CSS and nevertheless it deserve a glorious mention.

    Default rendering: Original Size (cannot be scaled, only positioned)

    However,

    CSS3's background-size: property improved on it by allowing multiple scaling options:

    Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

    [length> | | auto ]{1,2} | cover | contain

    But even with this property, it depends on container size.

    Still a good candidate method, see conclusions...



    CSS2's list-style: property along with display: list-item:

    First W3C Recommendation: Cascading Style Sheets, level 2 CSS2 Specification 12 May 1998

    list-style-image: property sets the image that will be used as the list item marker (bullet)

    The list properties describe basic visual formatting of lists: they allow style sheets to specify the marker type (image, glyph, or number)

    display: list-item — This value causes an element (e.g.,

  • in HTML) to generate a principal block box and a marker box.

    .myClass {
        display: list-item;
        list-style-position: inside;
        list-style-image: url("someimage.jpg");
    }
    

    Shorthand CSS: ( )

    .myClass {
        display: list-item;
        list-style: square inside url("someimage.jpg");
    }
    

    Default rendering: Original Size (does not depend on explicit size declaration)

    Restrictions:

    • Inheritance will transfer the 'list-style' values from OL and UL elements to LI elements. This is the recommended way to specify list style information.

    • They do not allow authors to specify distinct style (colors, fonts, alignment, etc.) for the list marker or adjust its position

    This method is also not suitable for the tag as the conversion cannot be made between element types, and here's the limited, non compliant hack that doesn't work on Chrome.

    Good candidate method, see conclusions...



    CSS3's border-image: property recommendation:

    Latest W3C Status: Candidate Recommendation CSS Backgrounds and Borders Module Level 3 9 September 2014

    A background-type method that relies on specifying sizes in a rather peculiar manner (not defined for this use case) and fallback border properties so far (eg. border: solid):

    Note that, even though they never cause a scrolling mechanism, outset images may still be clipped by an ancestor or by the viewport.

    This example illustrates the image being composed only as a bottom-right corner decoration:

    .myClass {
        border: solid;
        border-width: 0 480px 320px 0;
        border-image: url("http://i.imgur.com/uKnMvyp.jpg") 0 100% 100% 0;
    }
    

    Applies to: All elements, except internal table elements when border-collapse: collapse

    Still it can't change an 's tag src (but here's a hack), instead we can decorate it:

    .myClass {
        border: solid;
        border-width: 0 96px 96px 0;
        border-image: url("http://upload.wikimedia.org/wikipedia/commons/9/95/Christmas_bell_icon_1.png") 
                      0 100% 100% 0;
    }

    Good candidate method to be considered after standards propagate.



    CSS3's element() notation working draft is worth a mention also:

    Note: The element() function only reproduces the appearance of the referenced element, not the actual content and its structure.

    wolf cat

    We'll use the rendered contents of one of the two hidden images to change the image background in #img1 based on the ID Selector via CSS:

    #img1 {
        width: 480px; 
        height: 320px; 
        background: -moz-element(#pic1) no-repeat;
        background-size: 100% 100%;
    }
    
    .hide {display: none}
    

    Notes: It's experimental and only works with the -moz prefix in Firefox and only over background or background-image properties, also needs sizes specified.

    • element() Live Demo

    Conclusions

    1. Any semantic content or structural information goes in HTML.
    2. Styling and presentational information goes in CSS.
    3. For SEO purposes, don't hide meaningful images in CSS.
    4. Background graphics are usually disabled when printing.
    5. Custom tags could be used and styled from CSS, but primitive versions of Internet Explorer do not understand](IE not styling HTML5 tags (with shiv)) without Javascript or CSS guidance.
    6. SPA's (Single Page Applications), by design, usually incorporate images in the background

    Having said that, let's explore HTML tags fit for image display:

    The
  • element [HTML4.01+]
  • Perfect usecase of the list-style-image with display: list-item method.

    The

  • element, can be empty, allows flow content and it's even permitted to omit the
  • end tag.

    .bulletPics > li {display: list-item}
    #img1 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/4/4d/Nuvola_erotic.png")}
    #img2 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/7/74/Globe_icon_2014-06-26_22-09.png")}
    #img3 {list-style: square inside url("http://upload.wikimedia.org/wikipedia/commons/c/c4/Kiwi_fruit.jpg")}
    • movie
    • earth
    • kiwi

    Limitations: hard to style (width: or float: might help)

    The
    element [HTML5+]

    The figure element represents some flow content, optionally with a caption, that is self-contained (like a complete sentence) and is typically referenced as a single unit from the main flow of the document.

    The element is valid with no content, but is recommended to contain a

    .

    The element can thus be used to annotate illustrations, diagrams, photos, code listings, etc.

    Default rendering: the element is right aligned, with both left and right padding!

    • FIGURE Live Demo

    The element [HTML4+]

    To include images, authors may use the OBJECT element or the IMG element.

    The data attribute is required and can have a valid MIME type as a value!

    
    

    Note: a trick to make use of the tag from CSS would be to set a custom valid MimeType x-image/x followed by no data (value has no data after the required comma ,)

    Default rendering: 300 x 150px, but size can be specified either in HTML or CSS.

    • OBJECT Live Demo

    The tag

    Needs a SVG capable browser and has a element for raster images

    • SVG Live Demo

    The element [HTML5+].

    The width attribute defaults to 300, and the height attribute defaults to 150.

    • CANVAS Live Demo

    The element with type="image"

    Limitations:

    ... the element is expected to appear button-like to indicate that the element is a button.

    which Chrome follows and renders a 4x4px empty square when no text

    Partial solution, set value=" ":

    
    
    • INPUT type=image Live Demo

    Also watch out for the upcoming element in HTML5.1, currently a working draft.

    提交回复
    热议问题