In making my website I came upon a puzzle I couldn't solve, even with the help of the [very smart] internet.
In making my website I came upon a puzzle I couldn’t solve, even with the help of the [very smart] internet.
I needed to center a DIV within another DIV, but I needed the width of the inner div to stay malleable and flexible.
There are several super-helpful centering guides, like this one using pseudo-elements and this one, (both on css-tricks.com) — but none of quite answered my question. Some solutions require you to know the width of the inner DIV, and I couldn’t know that. The Table solution could have worked, but I was determined to avoid it, on principle, and pseudo-elements aren’t supported by all browsers.
It took some finagling, but I came up with a way. I do not claim to be the first (or best), but this is what made sense to me.
Step 1: Set up your outer containers
- Create the outermost container that you want to center things in, here with a class container.
- Wrap your text inside two separate divs, .step1 (the outer of the two) and .step2 (the inner of the two).
- For .step1, set the CSS properties of float:left, position:relative and left:50%.
In the “results” tab of the code snippet below, you can see .step1 with a pink background and .step2 with a black border. Notice that for now, they’re completely overlapping, and the positioning of .step1 has placed its left edge on the center line.
<div class="step2">My text.</div>
Step 2: Position your inner div
Now we look at .step2. We set float:left and position:relative here too, but we set its position at left:-50%. Now in the example below, you can see that .step2 has moved so that its center lines up with the center of our outer .container div. (Technically, its center is placed on the .step1 div’s left edge — which we know from above is placed on the center line of our outer container.)
Step 3: Style away
Once we make .step1 transparent and style .step2 more how we want it, we see only a nicely centered div, no matter how wide our text is. Hooray!
Important note about page width
Note that even though we’ve made .step1 transparent, it’s still there. Since we don’t want its width to expand past the width of the container and give us a horizontal scrollbar, it’s a good idea to add overflow:hidden to the .container div.
Bonus step: Center your text over an image
No worries, we can do this. All you need to do is place your image in your html inside the .container div and before .step1. Then we size the container to fit the picture and re-position our .step1 div. To do this, we add into our css for .step1 a setting of margin-top:-200px. This brings the div up on our page and into the picture, horizontally centered. Go team!
font: 18px/24px Georgia;
margin: 10px auto;
margin: 0 auto;
background-color: rgba(0, 0, 50, 0.4);
Questions? Have a better way? Let me know in the comments.