How to Position Backgrounds in CSS
Backgrounds in CSS may be positioned with keywords or percentage values. Let's take a look at how it works.
Positioning Backgrounds with Keywords.
Backgrounds may be positioned with the combination of the keywords: top
, left
, bottom
, right
, and center
Example
background-position: top left
The best way to see this at work is to use the playground below:
Change the background-position
value to use a combination of the keywords discussed. Observe how this affects the position of the background image.
Positioning Backgrounds with Length Values.
Generally, positioning in CSS follows a coordinate system. With respect to the top of the container element, the coordinate looks like so:
That being said, we could position the background image like so:
Where x
and y
represent length values e.g 14px
, 3em
… originating from the top left corner of the container element.
Positive length values are in the direction displayed above, and negative directions in the opposite directions.
Go ahead and try these in the playground below. Use length values to position the background image.
Positioning Backgrounds with Percentage Values.
Positioning backgrounds with percentage values act just like using length values but with a little twist.
With length values, the placement origin of the positioned background is the top left corner.
With percentages, the background isn’t positioned with respect to the top left corner. It is positioned with respect to the width or height of the image as per the percentage specified.
I know that sounds complicated. Here’s an example:
The result of background-position: 50% 50%
is represented in the image below:
50% into the parent container, and 50% into the child element. That’s how the confluence point is reached (please refer to the graphic above)
And here is background-position: 100% 100%
represented below:
Here is a playground to toy with setting background positions in percentages.
NOTE: By default the
background-position
is set to0% 0%
i.e if you do not set this property, it takes on this value by default
One more lesson, and we will get back to finishing off the movie project!