Skip to main content
Inspiring
Sep 24, 2018 11:40 PM UTC
Answered

(CSS) Can I make background-size 'contain' or 'cover' do this?

I've been toying with full-size background images, alternating between background-size: cover and contain. After some testing, I'm wondering if the behavior I'm looking for is even doable. Thought I'd ask here.

The image is of a standing silhouette.

The behavior I'm looking for is :

  • PROPORTIONALLY:
    Must retain original proportions at all times.
  • VERTICALLY:
    Must stretch to fill 100% viewport height at all times.
  • HORIZONTALLY:
    - If width is larger than image, left-justify.
    - If width is narrower, right-justify.
    (In other words, crop left side out of the viewport so the right side of the image remains in view.)

What is the simplest and most code-efficient way to obtain this result?

Thanks!

    This topic is closed to new replies. Start a new post to keep the conversation going.
    Under S.Correct answer
    Inspiring
    Sep 25, 2018 12:46 AM UTC

    Found it! Or close enough behavior that my original plans for the layout don't need to be trashed.

    Here it is, in case anyone wants to try anything similar :

    div#bg {

        background-image: url(/images/bg-main.png);

        height: 100%;

        width: 50%;

        background-size: cover;

        background-position: right;

        background-repeat: no-repeat;

    }

    (with the appropriate adjustments to html+body to remove margins and stuff)

    Sorry for wasting everyone's time with this one. For whatever reason, I kept trying to trick my way around left-justifying the image when it should've been right-justified the whole time.

    3 replies

    Under S.AuthorCorrect answer
    Inspiring
    Sep 25, 2018 12:46 AM UTC

    Found it! Or close enough behavior that my original plans for the layout don't need to be trashed.

    Here it is, in case anyone wants to try anything similar :

    div#bg {

        background-image: url(/images/bg-main.png);

        height: 100%;

        width: 50%;

        background-size: cover;

        background-position: right;

        background-repeat: no-repeat;

    }

    (with the appropriate adjustments to html+body to remove margins and stuff)

    Sorry for wasting everyone's time with this one. For whatever reason, I kept trying to trick my way around left-justifying the image when it should've been right-justified the whole time.

    Translate
    ALsp
    Legend
    Sep 25, 2018 12:02 AM UTC

    Post the actual image and let's have a play with it.

    Translate
    Nancy OShea
    Community Expert
    Community Expert
    Sep 24, 2018 11:51 PM UTC

    Probably best done with two separate images and different media queries for when things begin to fall apart

    Translate
    Nancy O'Shea— Product User & Community Expert