I'm trying to define a block smaller than the full width of the screen and then have that block centered horizontally. I can get it to work with IE7, but not with Opera9 or Firefox2, which leads me to believe there is something wrong with my approach, even though the HTML and CSS validates.

Here's the page:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en-us">
<head><title>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<STYLE type="text/css">
.block
{	width: 200px;
	background-color:#ff0;}
</style></head>
<body>
	<div style=text-align:center>
		<div class=block>text</div>
	</div>
</BODY></html>

How can I get that yellow container centered horizontally on the page, using valid HTML & CSS (not using a table)?

Dani AI

Generated

used a parent with text-align:center, which only centers inline-level content. was right to point toward auto margins: setting left/right margins to auto is the standard way to horizontally center a block-level element that has an explicit width and is not floated or absolutely positioned. See the MDN docs on the margin shorthand for details (margin on MDN).

A simple, robust pattern:

.centered-box {
  width: 320px;
  margin: 0 auto;    /* centers horizontally */
  background: #f9f871;
}

If the parent technique with text-align:center is preferred (for example to center multiple inline blocks), make the child inline-block instead of a normal block:

.parent { text-align: center; }
.inline-box {
  display: inline-block;
  width: 320px;
  background: #f9f871;
  text-align: left;   /* restore inner text alignment if needed */
}

For modern layouts, a single-line flexbox rule on the parent is even simpler:

.parent-flex { display: flex; justify-content: center; }

If margin: 0 auto seems not to work, check for common blockers: the element is floated, absolutely positioned, has no width, or a more specific rule overrides the margins. Developer tools (Inspector) are useful to view computed styles and see which rule applies. For background reading on centering behavior and text-align, see text-align on MDN.

Recommended Answers

All 2 Replies

<div "style=margin: auto">

Thanks for the "reminder," stymiee.

Of course, I have used that very tag several times, but for some reason faced a mental block this time.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.