Skip to main content
Inspiring
September 24, 2018
Answered

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

  • September 24, 2018
  • 3 replies
  • 467 views

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 has been closed for replies.
    Correct answer Under S.

    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
    September 25, 2018

    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.

    ALsp
    Legend
    September 25, 2018

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

    Nancy OShea
    Community Expert
    Community Expert
    September 24, 2018

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

    Nancy O'Shea— Product User & Community Expert