Gregg
Gregg

Reputation: 495

How to set a minimum width with background-size

I have an image that is 1000px X 600px . I want to use it as a responsive background for a div but would like to set a minimum width of 1000px despite how small the browser window is.

This is frustrating because there doesn't seem to be a simple way to define a min. width.

If I use background-size: cover - for some reason, the image is defaulted much larger than 1000px.

please help

Upvotes: 13

Views: 47251

Answers (4)

Alexander Goncharov
Alexander Goncharov

Reputation: 1662

You can use calc in background-size:

.bg {
    background-size: calc(max(100%, 1000px));
}

calc works also with background-position, for one side, or both sides

Upvotes: 4

Chris Barrell
Chris Barrell

Reputation: 101

There's now an option for background-size to only scale the image until the picture has met it actual height/width. This way, you don't have to set a min-width or anything.

In your CSS:

body {
  background-size: cover;
}

Reference: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size#Values

Upvotes: 8

Maxfield Solar
Maxfield Solar

Reputation: 131

I had the same problem. The following code worked for me. I just had to add a min width in the same element. Here I just used the html element, I would assume that it would be more conventional to use the body element

     /* CSS Style Sheet */

 html    { background-image:url(example.JPG);
                    background-size:cover;
                    min-width:1000px;}

I hope this helps,

Upvotes: 3

Craig
Craig

Reputation: 691

If media queries are an option, you can setup a media query for browser viewports smaller than 1000px wide.

Assuming your HTML viewport is set:

<meta name="viewport" content="width=device-width">

And your div is named 'bg':

<div class="bg"></div>

In your CSS:

.bg {
    width: auto; /* Scale the div to the parent width */
    height: 900px; /* The div needs some height to be visible */
    background-image: url(bg.png); /* This is your background image */
    background-size: 100%; /* Always size the image to the width of the div */
    background-position: top; /* Position the image to the top center of the div */
}

/* For any viewports less than 1000px wide */
@media (max-width: 1000px) {

    .bg {
        background-size: 1000px 600px; /* Force the image to its minimum width */
    }

}

Upvotes: 20

Related Questions