If old browsers are not an issue, use HTML5 / CSS3. If they are, apply polyfills and still use HTML5 / CSS3. I assume that your div has no margins or paddings here, but they are relatively easy to account for. The code follows.
.centered {
position: relative;
left: 50%;
transform: translateX(-50%);
}
What this does is:
- Position the
div
relative to its container;
- Position the
div
's left boundary at 50% of its container width horizontally;
- Translate back horizontally by 50% of the
div
's own width.
It is easy to imagine this process to confirm that the div
would be horizontally centered eventually. As a bonus, you can center vertically at no additional cost:
.centered-vertically {
position: relative;
top: 50%;
transform: translateY(-50%);
}
The advantage of this approach is that you don't have to do any counterintuitive stuff, such as considering your div a text of sorts, wrapping it in a (often semantically useless) additional container, or giving it a fixed width, which is not always possible.
Don't forget vendor prefixes for transform
if needed.