This question already has an answer here:
- How to horizontally center a <div>? 93 answers
I'm trying to horizontally center a <div>
block element on a page and have it set to a minimum width. What is the simplest way to do this? I want the <div>
element to be inline with rest of my page. I'll try to draw an example:
page text page text page text page text
page text page text page text page text
-------
| div |
-------
page text page text page text page text
page text page text page text page text
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.
What this does is:
div
relative to its container;div
's left boundary at 50% of its container width horizontally;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: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.you can use the position:relative; and then set the left and the top values:
If your
<div>
hasposition: absolute
you need to usewidth: 100%;
The best response to this question is to use
margin-auto
but for using it you must know thewidth
of yourdiv
inpx
or%
.CSS code:
Using jQuery:
or, if you want to center every element with class ".myElement":
CSS, HTML:
Your diagram shows a block level element also (which a div usually is), not an inline one.
Of the top of my head,
min-width
is supported in FF2+/Safari3+/IE7+. Can be done for IE6 using hackety CSS, or a simple bit of JS.