0

What are the minimum style declaration requirements for an element that I want to horizontally center with margin:0 auto;?

And the minimum requirements style declaration for the containing elment(s)?

I would like the solution to be element-type agnostic, i.e. to be working no matter if it's a span, div, a etc.

The solution should work in any modern browser.

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232
  • Are you 100% sure that the information given there works in any given situation? I'm fully aware that there exists millions of posts about this subject, but I've been very precise about the neutral conditions. – Fellow Stranger Sep 18 '13 at 12:14

3 Answers3

2

Here's a generic class with the minimum amount of required properties (avoid using the margin: 0 auto short-hand so you don't unnecessarily override the margin-top and margin-bottom properties):

.horizontal-center {
    margin-right: auto;
    margin-left: auto;
    display: block;
    width: 80%; /* any value other than auto */
}

The only constraint on .horizontal-center's parent is that it needs display: block|inline-block and a width greater or equal to .horizontal-center's.

André Dion
  • 21,269
  • 7
  • 56
  • 60
1

You have to specify width too, because if there is no width on a block-level element, it just takes all 100% of the horizontal space.

For tags like span or a, you have to make them display block.

Jakub Kotrs
  • 5,823
  • 1
  • 14
  • 30
1

for center horizontaly you have to specify width of an element and u cant not use float property.

Love Trivedi
  • 3,899
  • 3
  • 20
  • 26