CSS Image Centering
In this page:
Horizontal Centering with margin: auto
A block-level image (display: block, which images aren't by default) with a fixed width and margin: 0 auto centers itself horizontally within its containing block — this is the oldest and simplest centering technique and still the right tool for basic cases.
Example: Horizontal Centering with margin: auto
<style>
img {
display: block;
width: 150px;
margin: 0 auto;
}
</style>
<img src="https://placehold.co/150x100" alt="Centered">
Centering with text-align
If an image is left as its default inline/inline-block display, wrapping it in a block-level parent with text-align: center centers it horizontally the same way it would center a line of text, without needing to touch the image's own display or margin.
Example: Centering with text-align
<style>
.wrap {
text-align: center;
}
</style>
<div class="wrap">
<img src="https://placehold.co/150x100" alt="Centered like a line of text">
</div>
Flexbox Centering (Both Axes)
Setting display: flex on a container along with justify-content: center and align-items: center centers its image child on both axes at once, and works regardless of whether the image's or container's exact dimensions are known ahead of time.
Example: Flexbox Centering (Both Axes)
<style>
.wrap {
display: flex;
justify-content: center;
align-items: center;
height: 150px;
}
</style>
<div class="wrap">
<img src="https://placehold.co/100x80" alt="Centered on both axes">
</div>
Absolute Positioning with transform
Positioning an image absolutely at top: 50%; left: 50% moves its top-left corner to the container's center, and adding transform: translate(-50%, -50%) then shifts it back by exactly half its own size — perfectly centering it without flexbox or grid.
Example: Absolute Positioning with transform
<style>
.wrap {
position: relative;
height: 150px;
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="wrap">
<img src="https://placehold.co/100x80" alt="Centered without flexbox">
</div>
Grid Centering
A single-cell CSS Grid container with place-items: center centers its image child on both axes in one declaration, functionally equivalent to the flexbox approach but often considered more concise for this specific single-item case.
Example: Grid Centering
<style>
.wrap {
display: grid;
place-items: center;
height: 150px;
}
</style>
<div class="wrap">
<img src="https://placehold.co/100x80" alt="Centered in one declaration">
</div>
Chapter Quiz — Complete all 22 topics to unlock
0/22 topics done
Complete these topics first:
- CSS Gradients
- CSS Shadows
- CSS Filters
- CSS Blend Modes
- CSS Transforms
- CSS 2D Transforms
- CSS 3D Transforms
- CSS Transitions
- CSS Animations
- CSS Image Styling
- CSS Image Effects
- CSS Hover Overlays
- CSS Image Modal
- CSS Image Centering
- CSS Image Shapes
- CSS Buttons
- CSS Columns
- CSS Clip Path
- CSS Shapes
- CSS Scroll Snap
- CSS Architecture: BEM
- CSS Custom Properties