I have set the div to inline-block and set the margin to (0 auto). Why doesn't it work?

- 1,291
- 2
- 16
- 21
-
or you know provide your markup instead of a random screenshot? – N. Ivanov Aug 21 '17 at 08:30
-
2Possible duplicate of [How to horizontally center ain another– Paolo Forgia Aug 21 '17 at 08:30?](https://stackoverflow.com/questions/114543/how-to-horizontally-center-a-div-in-another-div)
-
It's not working because margin: o auto will affect divs/blocks with display: block and defined width, like here: https://codepen.io/TunderScripts/pen/ayYjXX – Dinca Adrian Aug 21 '17 at 08:37
-
Because it is an `inline-block` element, which means it obeys the `inline` properties (you cannot assign left/right auto margins to inline elements). – Terry Aug 21 '17 at 08:37
3 Answers
You should use text-align: center;
to center elements with text. Divs actually have 100% width, so they cannot be centered unless you set them width property.

- 67
- 1
- 1
- 9
-
While by default a `div` is indeed a block-level element, the OP clearly states that the element is set with `display: inline-block`, so it's actually not expanding to 100%. Though in this case, the OP can set `text-align: center` on the _parent_ `div`. – Boaz Aug 21 '17 at 08:36
- An inline block lays out its content like a block, but is laid out inline in its parent and you can have text before and after on the same line, so auto-margins don't do any kind of centering, just like they would not on a span. You need to be
display: block
for automargins to center things
2.a. If you had display: block
it still wouldn't work, as by default they fill the whole width. auto margins center things by equaly distributing leftover space to both side, but you need to have leftover space to begin with. try using the width
or max-width
properties. If you do not have a fixed width, and want something that depends on the size of the content, try width: fit-content
/ width: -moz-fit-content
/ width: -webkit-fit-content
(https://developer.mozilla.org/en-US/docs/Web/CSS/width#fit-content).
2.b. Alternatively, depending on exactly what you're after, instead of centering the div in its parent, you may want to center the text inside the div, with text-align: center
. You'll still need to make the div a block rather than an inline block, otherwise its width will be that of the text it contains, and there won't be any centering possible.

- 491
- 4
- 8