Last Updated: September 09, 2019
·
5.522K
· elad2412

The New Background Position in CSS3

Hello everybody. I assume that most of you have used or experienced with background-position.

Introduction

in background-position prior to css3 you set the position from the top left of the element.
For Example:

div{background-position:20px 40px;/*20px from left & 20px from top*/}

The problem was that it isn't possible to determine exact position from another point, for example from bottom / right, I can only start from left top!

We can write: background-position: right bottom; and we can write: background position:70%/from left/ 80%/from top/;,
but we can't write 20px from right and 20px from the bottom.

Picture

Say Hello to the New Background Position

To solve this issue, CSS3 provide us with the option to determine from where to begin the positioning and by that to determining what will be the 0,0 point.

Picture

How It Works?

Instead of writing only 2 values (horizontal and vertical point from left top), we can now with css3 write the begin of the horizontal and vertical position, like right bottom + the value from the start point.

Let's create an example:

First create a empty div with some styles:

HTML

<div class="box">
</div>   

CSS

.box{   
  width:300px;
  height:300px;
  background-color:#ddd;
  padding:10px;
  border:solid 3px #333;
  border-radius:10px;
}

Now we’ll add a background-image with fixed background-size (new feature in CSS3).

.box{   
    background:url(images/image.jpg) no-repeat;
    background-size:150px 150px;
}

And finally we’ll add the New Background Position.

First we set the horizontal starting point, for example: right and after we can set the distance we want from that position, for example 20px.
Second we set vertical begin start point, for example: bottom and after we set the distance we want from that position, for example 40px.

** CSS new background-position**

.box{ background-position :right 20px bottom 40px;}

This is what will get:

Picture

Live Example

Yeay! we did it.

You also can make a box with multiple background images and every image determine in other corner, like in this example.

Support

  • Work in all new browsers except safari.
  • IE - works from IE9 and above.
  • Chrome mobile - isn't support - User Report

That’s all, I hope you enjoy it.

If you like this post, I will be happy to get your UPVOTE. You are welcome to follow me or my team @Walla! R&D and endorse my skills.

Elad Shechter.

7 Responses
Add your response

Nice one. :)

over 1 year ago ·

This does not work in Safari 6.0.5.

over 1 year ago ·

@thomaslindstr_m , 10X for checking

over 1 year ago ·

would it also be possible to use ::before/::after with the bg image and just absolutely position inside the container. Would have more support.

over 1 year ago ·

Very nice Shechter

over 1 year ago ·

Doesn't work on Chrome Mobile.

over 1 year ago ·

The images in your codepen examples are private.

over 1 year ago ·