Cameron
Cameron

Reputation: 28803

Prevent repeating background from clipping

I have the following example: http://jsfiddle.net/umxvq52j/ of a repeat background of stars.

CSS:

.stars
{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 320px;
    background: url('http://i59.tinypic.com/2i95zzk.png') left center repeat-x;
}

What I want to do is make it so that the stars perfectly fill the space and you don't get the edges of the stars cropped! So if I'm on a smaller screen it will show 2-3 stars flush, then 6-7 etc, and never show half a star.

Is this possible?

Upvotes: 10

Views: 1678

Answers (4)

Tanisha Bisht
Tanisha Bisht

Reputation: 49

Use this to prevent background from clipping

background-repeat: space;

Upvotes: 1

Nick
Nick

Reputation: 3281

For the best browser support and if you don't mind JavaScript and a bit more typing:

Fiddle

HTML:

<div class="stars_con">
<div class="stars"></div>
</div>

CSS:

.stars_con
{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 320px;

}
.stars{
    background: url('http://i59.tinypic.com/2i95zzk.png') left center repeat-x;
    width:100%;height: 320px;
}

JS:

$(window).on("resize load", function () {
    var screenWidth = $(window).width();
    var starWidth = 320;
    var width = screenWidth - (screenWidth % starWidth);
    $('.stars').css({
        'width': width
    });
});

Upvotes: 6

VeldMuijz
VeldMuijz

Reputation: 615

You could do something pretty hacky and if you have set measurements on your images: jsfiddle here

.stars
{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 320px;
    background: url('http://placehold.it/200x200') left center repeat-x;
}

@media screen and (max-width: 600px) {
    .stars
{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 320px;
    background: url('http://placehold.it/200x200'),url('http://placehold.it/200x200'); 
    background-position: left, right;
    background-repeat: no-repeat, no-repeat;
}
}

Upvotes: 0

Jaay
Jaay

Reputation: 2153

I don't know if this is what you are looking for but take a look at the round attribute of background

background: url('http://i59.tinypic.com/2i95zzk.png') round 0 0;

Credit goes to CSS3 background spacing

Upvotes: 7

Related Questions