How to Align an Image in HTML, CSS, and Markdown
Learn how to align an image using HTML, CSS, flexbox, grid, Markdown, and React with clear examples, responsive tips, and accessibility guidance.
You’ve got the cursor in the right place, but the page still looks wrong. The image is either floating off to one side, sitting awkwardly inside a card, or drifting on mobile after it looked perfect in desktop preview. That’s usually the moment people search for how to align an image, and it’s also where half the advice online starts talking past the actual problem.
The confusion comes from one phrase covering two different jobs. In web work, layout alignment means centering or positioning the image box inside a page. In imaging and computer vision, visual registration means lining up the pixels of two images so their content matches. The same query can mean “center this hero image in CSS” or “make these before-and-after screenshots line up.” If you’re also thinking about broader interface decisions, a good primer on user interface design helps explain why alignment choices affect readability, not just aesthetics.
For front-end work, this guide stays focused on HTML, CSS, Markdown, MDX, React, and Tailwind. It leaves panorama stitching and image registration pipelines to the vision folks, except where it helps clarify the ambiguity. The practical mental model is simple, the box is layout, the pixels are registration. If you keep that split in your head, the rest of the fixes get much easier.
Table of Contents
- What “Align an Image” Means in 2026
- Classic CSS Techniques Worth Keeping
- Flexbox and Grid for Modern Layouts
- Vertical and Responsive Alignment
- Markdown, MDX, and React/Tailwind
- Accessibility and SEO Considerations
- Choosing the Right Method and What Comes Next
What “Align an Image” Means in 2026
A developer usually finds the ambiguity the hard way. One person wants a product hero image centered in a blog post, another wants two screenshots to line up at the edges after a redesign, and both ask the same thing, how do I align an image. Search results mix CSS recipes with visual correction tools, so the first job is to separate box alignment from image registration.
The two meanings are not interchangeable
Layout alignment is about where the image sits in the document flow. You’re centering an <img>, lining it up with text, or keeping it from breaking a card layout. That’s the world of text-align, margin: auto, flexbox, grid, and wrappers.
Visual registration is different. In technical image alignment, methods map two or more images into a shared coordinate system so they can be compared, merged, or stitched, and feature-based workflows often estimate a homography from 4 or more corresponding points with least-squares fitting and RANSAC-style outlier rejection for better reliability when matches are messy. That matters for stitching and panoramic imaging, where the transform turns overlapping photos into a single mosaic rather than a set of misregistered frames. The same field commonly uses L2, L1, or normalized correlation depending on whether the task values noise sensitivity, outlier handling, or structural similarity, as summarized in Cornell’s alignment lecture material on image alignment fundamentals.
Practical rule: if you’re editing HTML, CSS, Markdown, or MDX, you’re probably solving layout alignment. If you’re comparing camera angles, screenshots, or microscope frames, you’re in registration territory.
What this article covers
The rest of the article is for people building web pages, docs, or UI components. That means the useful tools are the ones that ship, like text-align: center, flexbox, grid, responsive wrappers, and Markdown patterns that survive copy-paste into real docs. The goal is to get the image to behave inside a layout without creating a second bug somewhere else.
The tricky part is that the same fix can look right on desktop and fail on mobile. A centered image can still be too wide, cropped badly, or semantically wrong even when it looks aligned. If you also care about broader interface decisions, a primer on user interface design helps show why alignment choices affect readability, not just appearance.
Classic CSS Techniques Worth Keeping
Old CSS still shows up in codebases, CMS themes, email templates, and documentation exports. You’ll still see people reach for floats, centering tricks, and legacy attributes because they were the first tools available, and in a few places they still work fine. The key is knowing when you’re using a stable pattern versus when you’re maintaining an old habit.

text-align is still the quickest centering move
If the image is inline or treated like inline content, center the parent with text-align: center;. That’s the cleanest way to center an image in blog output, Markdown-rendered content, and simple article layouts.
.post-body {
text-align: center;
}
.post-body img {
max-width: 100%;
height: auto;
}
This works because the image participates in inline formatting, so the parent’s text alignment affects it. It’s simple, readable, and still the right answer when you’re not building a component-heavy interface.
Good default: use
text-align: centerfor content-driven pages where the image is part of a paragraph-like flow.
margin: auto only works when the image is block-level
margin: 0 auto; is a solid centering trick, but it won’t do anything useful on a default inline <img>. Make the image a block element first.
img.centered {
display: block;
margin: 0 auto;
max-width: 100%;
height: auto;
}
That pattern is useful when you want the image centered and you don’t want to rely on the parent’s text alignment. It’s also a good fit when the image is the only child inside a container.
Floats and the align attribute are legacy, not a new plan
Floats still exist in older layouts and some email-safe templates, but they’re mostly a maintenance concern now. The deprecated align attribute belongs in the same bucket. If you see it in an old article or template, read it as history, not a best practice.
For a lot of technical writers, the skill is recognizing a 2015 tutorial and not copying its habits into 2026 code. That matters more than memorizing another centering trick.
Flexbox and Grid for Modern Layouts
Flexbox is the modern default when the goal is to align an image inside a component. It handles horizontal and vertical centering without extra wrapper hacks, and the code reads like what the layout is doing. Grid is the better choice when the image needs to align with other blocks, not just sit in the center of a single container.
Flexbox handles the common case cleanly
.hero {
display: flex;
justify-content: center;
align-items: center;
min-height: 320px;
}
.hero img {
max-width: 100%;
height: auto;
}
That snippet centers the image both ways, as long as display: flex lands on the correct parent. The most common mistake is applying flex to the image itself or to a wrapper that isn’t controlling the space you care about. When that happens, nothing seems broken in the CSS, but the image still sits in the wrong place.
Grid shines when the image shares space with other content
.feature {
display: grid;
grid-template-columns: 1fr auto;
align-items: center;
gap: 1rem;
}
.feature img {
max-width: 100%;
height: auto;
}
Grid is useful when the image sits beside text, labels, or controls. It gives you a stronger structural model than flexbox when you’re arranging multiple tracks and want alignment rules to stay predictable.
justify-content: center is often enough on a flex container, so margin: auto on the image itself can become redundant. It doesn’t hurt in every case, but it’s not the thing doing the work when the parent already controls alignment. For responsive UI work, max-width: 100% and height: auto keep the image from blowing past its container while it stays centered.
When the image belongs to a component, align the component first. The image usually behaves after that.
Use the layout tool that matches the container
If the parent is a simple content box, flexbox is usually enough. If the image has to line up with other interface elements, grid is often cleaner. If the content is just an article body, text-align can still be the fastest answer.
Vertical and Responsive Alignment
A centered image can look correct in one viewport and drift in the next. Vertical alignment usually breaks because the container changes height, the image changes shape, or both. The fix is rarely a single declaration. It is usually a combination of container sizing, fit behavior, and a clear decision about whether cropping is acceptable.

Vertical centering works best when the container is explicit
.frame {
display: flex;
align-items: center;
justify-content: center;
min-height: 240px;
}
.frame img {
max-width: 100%;
height: auto;
}
If the parent does not have a real height or min-height, there is nothing stable for vertical centering to work against. Flexbox handles this cleanly once the container defines that space. Grid can do the same job with less code.
.frame {
display: grid;
place-items: center;
min-height: 240px;
}
Use the layout method that matches the box you control. When the height belongs to the container, centering becomes predictable instead of dependent on the image’s natural size.
Preserve proportion instead of forcing stretch
A common failure mode is stretching or cropping the image until the visual center shifts. The safer pattern is to keep the image proportional with aspect-ratio, then decide whether the image should fit inside the box or cover it.
.media {
aspect-ratio: 16 / 9;
overflow: hidden;
}
.media img {
width: 100%;
height: 100%;
object-fit: cover;
}
object-fit: cover works well when a consistent frame matters and a crop is acceptable. If the crop would hide important content, leave object-fit off and let the image scale naturally instead.
Responsive alignment usually fails on mobile first. A desktop preview can look centered because the image dimensions happen to match the container, then a phone view changes the intrinsic shape and the image slips off axis. A quick check across breakpoints is more useful than another small tweak to the alignment rule. If you are documenting that workflow for a team, a short tutorial checklist helps keep the validation step from getting skipped.
The practical checklist is short.
- Check the container height: without an explicit height, vertical centering may not show any visible effect.
- Confirm the image’s fit mode:
covercrops,containpreserves the full image. - Verify mobile dimensions: the image can drift when its displayed size changes.
- Avoid unwanted stretching: do not use width rules that distort the image just to force alignment.
- Test the actual breakpoints: desktop alignment can lie.
For teams documenting UI steps, the layout in the editor is not always the layout users see in the browser. That is why responsive validation matters before you publish or ship.
Markdown, MDX, and React/Tailwind
Markdown does not give you a native alignment syntax for images, so people end up mixing HTML and CSS into the content. That’s normal, and it’s usually the right move when the image needs to be centered consistently across a docs site or blog engine. The trick is to keep the Markdown readable and push the alignment into a wrapper or component.

Markdown usually needs an HTML wrapper
<div style="text-align:center;">
</div>
That works in some renderers, but many Markdown parsers treat the image syntax as Markdown, not as nested HTML content. A safer pattern is to use raw HTML for the image when you need tighter control.
<div class="image-center">
<img src="./screenshot.png" alt="Product screenshot" />
</div>
.image-center {
text-align: center;
}
In MDX, that same wrapper can become a reusable component, which is cleaner than repeating one-off style blocks in every file. A centered component also keeps docs teams from copy-pasting brittle alignment code into unrelated pages.
React and Tailwind make the pattern easy to repeat
export function CenteredImage({ src, alt }) {
return (
<div className="flex justify-center">
<img src={src} alt={alt} className="block max-w-full h-auto" />
</div>
);
}
For a wider layout, Tailwind’s mx-auto block max-w-full combination is still a reliable choice when the image itself needs to sit in a constrained container.
<img
src="/diagram.png"
alt="Architecture diagram"
className="block mx-auto max-w-full h-auto"
/>
That works well when the parent container already handles the page structure. If the image is inside a doc card or tutorial step, keep the wrapper responsible for spacing and alignment, and let the image stay focused on sizing.
A useful docs habit is to keep the alignment logic in a component, not scattered through every article. If your docs live in an MDX workflow, the formatting patterns for technical documentation page is a good reference for keeping reusable content clean.
Watch the Markdown flavor you’re publishing to
GitHub Flavored Markdown can behave differently from MDX or a site generator with custom components. A snippet that works in a docs app may fall apart in a README if the renderer strips the wrapper behavior or ignores embedded styles. Before you paste a pattern into source control, verify the target renderer supports it the same way.
Accessibility and SEO Considerations
A centered image isn’t automatically a better image. Alignment can improve clarity, but accessibility and search visibility depend more on semantic markup, alt text, and layout stability than on whether the image sits perfectly in the middle of the page. If you’ve ever fixed a visual issue and still seen the page feel broken, this is usually why.

Semantic structure matters more than old alignment habits
The first thing to check is the image’s purpose. If it carries meaning or needs a caption, use a <figure> with a <figcaption>, not a random centered <img> wrapped in extra divs just for appearance. That keeps the content understandable when someone uses a screen reader or scans the page out of context.
Alt text is more important than any alignment property. If the image is decorative, the alt text should reflect that. If it communicates information, the description should do real work.
Stable dimensions reduce the feeling that alignment is broken
Layout shift makes images look misaligned even when the CSS is technically correct. Declaring width and height up front helps the browser reserve space before the image loads, which keeps surrounding content from jumping around. Lazy loading helps with performance, but it still needs sensible dimensions to avoid a sloppy first paint.
For teams publishing docs or API references, clean image markup also helps the page stay easier to parse and maintain. The documentation guidance in how documentation pages rank and stay useful connects that hygiene to broader search visibility without relying on gimmicks.
A few checks are worth running before you publish.
- Alt text: describe the image’s meaning, not just that it exists.
- Dimensions: set width and height so the page doesn’t shift.
- Loading strategy: use lazy loading when the image isn’t immediately needed.
- Caption needs: choose
<figure>and<figcaption>when context matters. - Alignment method: pick the smallest technique that solves the layout problem.
If you care about inclusive interfaces, the broader discipline of designing for diverse audiences is the right lens. Alignment is one piece of that, not the whole story.
Choosing the Right Method and What Comes Next
If the image sits inside flowing content, text-align: center or a simple block wrapper is usually enough. If the image belongs to a component, flexbox is the default. If it’s part of a multi-column arrangement, grid tends to stay cleaner. If you’re in Markdown or MDX, wrap the image in HTML or a reusable component so the renderer doesn’t decide for you.
The other meaning of align an image belongs to a different toolchain. When two screenshots, microscope frames, or panorama sources need to match at the pixel level, you’re looking at visual registration, not page layout. That’s where homography-based pipelines, feature matching, and automated straightening tools live, and where manual centering tricks won’t help.
The best fix is still the simplest one that matches the problem. Ship semantic HTML, keep the layout responsive, and don’t reach for advanced registration unless the issue is content alignment between images, not the position of one image inside a box.
GitDocAI helps teams keep image-heavy docs, tutorials, and help centers in sync without reworking every page by hand. If you’re maintaining technical content where alignment, layout, and responsive rendering keep drifting between versions, take a look at GitDocAI and see how it fits into your publishing workflow.