Search code examples
htmlcssmargintext-alignmargin-left

Half margin when using text-align: center instead of text-align: left


I just figured out a strange behavior. I used a div with text-align: center and an inner div with display: inline-block to center the inner div. So nothing exciting so far. Then i added a left margin on the inner div, because I needed it to be shifted slightly to the right from the centered position. But the margin I added was always wrong and I just couldn't understand why. So I did some testing and figured out that when you use text-align: center you have to double the margin to get the right one, but why? I really would like to understand this behavior.

I made a quick fiddle, so you can see what i mean: https://jsfiddle.net/wnjg5ks4/

Just in case you don't understand this part:

.container2 {
    text-align: center;
    width: 400px;
    margin-left: -175px;
}

The margin-left: -175px is there to "delete" the "natural" space between the left and centered version, so it's easier to compare just the margins.


Solution

  • Your child element, .center, is being centered correctly. The red box AND it's margin are being centered. Since it's the only element, you were able to double the margin to get the desired shift, but the image below should help. The orange highlight is the margin.

    To just jog the element over a little, you could use transform:translateX(100px); or whatever value works for you.

    enter image description here