0
0
CssHow-ToBeginner · 3 min read

How to Set Background Position in CSS: Simple Guide

Use the background-position property in CSS to set where a background image appears inside an element. You can specify positions using keywords like top, center, bottom, or exact values like 50% 50% or 10px 20px.
📐

Syntax

The background-position property sets the starting position of a background image inside an element. It accepts two values: horizontal and vertical positions.

  • Keywords: left, center, right for horizontal; top, center, bottom for vertical.
  • Length values: pixels (px), ems (em), etc.
  • Percentages: relative to the element's size, e.g., 50% 50% centers the image.
css
background-position: horizontal vertical;
💻

Example

This example shows a background image positioned at the bottom right corner of a box using keywords, and then centered using percentages.

css
html {
  height: 100%;
  margin: 0;
}

body {
  height: 100vh;
  margin: 0;
  display: flex;
  gap: 20px;
  padding: 20px;
  background-color: #f0f0f0;
}

.box {
  width: 200px;
  height: 150px;
  border: 2px solid #333;
  background-image: url('https://via.placeholder.com/100');
  background-repeat: no-repeat;
}

.box.bottom-right {
  background-position: right bottom;
}

.box.center {
  background-position: 50% 50%;
}
Output
Two boxes side by side: left box shows a small image placed at the bottom right corner inside the box; right box shows the same image centered inside the box.
⚠️

Common Pitfalls

Common mistakes when using background-position include:

  • Using only one value, which sets the horizontal position but leaves vertical at default (50%).
  • Not specifying units for length values (e.g., writing 10 20 instead of 10px 20px).
  • Forgetting that percentages are relative to the element's size, not the image size.
css
/* Wrong: missing unit for length values */
.element {
  background-position: 10 20; /* Incorrect */
}

/* Correct: units included */
.element {
  background-position: 10px 20px;
}

/* One value sets horizontal, vertical defaults to center */
.element {
  background-position: left; /* vertical is 50% by default */
}
📊

Quick Reference

ValueDescriptionExample
left topImage placed at top-left cornerbackground-position: left top;
center centerImage centered horizontally and verticallybackground-position: center center;
right bottomImage placed at bottom-right cornerbackground-position: right bottom;
50% 50%Image centered using percentagesbackground-position: 50% 50%;
10px 20pxImage offset 10px from left, 20px from topbackground-position: 10px 20px;

Key Takeaways

Use two values in background-position to set horizontal and vertical placement.
Keywords like top, center, and bottom are easy ways to position backgrounds.
Percentages position the image relative to the element's size, not the image size.
Always include units like px when using length values.
If only one value is given, the vertical position defaults to center.