Multiple background-images and a background-color

前端 未结 2 1535
栀梦
栀梦 2020-12-03 15:16

Suppose I want to render an arrow in CSS, which should have a head, a tail and flexible width so it can contain text. I can of course create multiple divs to get what I want

相关标签:
2条回答
  • 2020-12-03 15:24

    No, it's not exactly lost from the shorthand declaration. You can still specify the background color, but only for the last (middle) layer (regardless of whether you put an image there):

    div.arrow {
        background: url('arrowtail.png') left no-repeat, 
                    url('arrowhead.png') right no-repeat, 
                    red;
    }
    

    Note that for your scenario, your images may have to have completely opaque backgrounds. The background color will show under any transparent pixels of your images.

    jsFiddle demo


    Declaring background-color separately, however, may be much better for your scenario as it lets you use different colors based on the same background images (if you're good with transparent pixels on the parts of your images to be filled with the CSS background color):

    div.arrow {
        background: url('arrowtail.png') left no-repeat, 
                    url('arrowhead.png') right no-repeat;
    }
    
    /* Assuming your red arrow has this ID */
    #red {
        background-color: red;
    }
    

    jsFiddle demo

    0 讨论(0)
  • 2020-12-03 15:39

    I find using multiple background images to be problematic for things like this. Have you considered using the :before and :after pseudo elements? I wrote up a quick example:

    <style>
        .arrow { display:block; margin:0; padding:0; width:200px; height:45px; line-height:45px; text-align:center; background:#ffffd; }
        .arrow:before { float:left; display:block; margin:0; padding:0; width:25px; height:45px; background:#ccc; content:''; }
        .arrow:after { float:right; display:block; margin:0; padding:0; width:25px; height:45px; background:#ccc; content:''; }
    </style>
    
    <div class="arrow">This text is on a transparent background</div>
    

    Just replace the background color in the :before and :after declarations to the arrow images you want.

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