How to include the background-cover value in the shorthand background property?

前端 未结 4 1787
遥遥无期
遥遥无期 2020-12-02 13:02

I am trying to set a background-image to stretch to the full extent of a

\'s width and height. The
will be of variable size,
4条回答
  •  无人及你
    2020-12-02 13:15

    The syntax of (multiple) background shorthand is:

    background: [ , ]*

    Where

    = || [ / ]? || || || ||

    = || [ / ]? || || || || || <'background-color'>

    ... If one value is present then it sets both ‘background-origin’ and ‘background-clip’ to that value. If two values are present, then the first sets ‘background-origin’ and the second ‘background-clip’.

    • A double bar (||) separates two or more options: one or more of them must occur, in any order.
    • An asterisk (*) indicates that the preceding type, word, or group occurs zero or more times.
    • A question mark (?) indicates that the preceding type, word, or group is optional.

    So the in order to include background-size, you must specify the background-position before it and place a / in-between.


    Assuming that you want to crop the image from the center instead of top-left you would write:

    background: url(...) center / cover;
    

    All four examples below use the same image:

    h1 {
      font: medium monospace;
    }
    .test {
      display: inline-block;
    }
    .test-landscape {
      width: 200px;
      height: 150px;
    }
    .test-portrait {
      width: 150px;
      height: 200px;
    }
    .test-lefttop {
      background: url(http://dummyimage.com/400x400/CCC/000000&text=%C3%97) left top / cover;
    }
    .test-center {
      background: url(http://dummyimage.com/400x400/CCC/000000&text=%C3%97) center / cover;
    }

    background-position: left top

    background-position: center

提交回复
热议问题