When i use just margin: auto for an element, it doesn't get centered, but when i add for the width a value it just get in the middle.
Asked
Active
Viewed 42 times
-1
-
1How would you propose to equally centre something you don't know the width of? ;) Elements will be full width by default unless specified – Andy Holmes Sep 01 '22 at 16:38
-
SHow example code – epascarello Sep 01 '22 at 16:55
-
This is a heading – lunatic Sep 01 '22 at 17:36
-
use text-align: center in this case – Temani Afif Sep 01 '22 at 19:46
2 Answers
2
You should add a width because by default the block-level elements such as a div, p, list, etc take up the full width of its parent element, and no space is left to adjust the element horizontally. So, the very first thing you need to check is whether you have set the width of the element for margin: auto to work.

Wayne Celestin
- 149
- 1
- 6
0
Adding a width to an element defines how much space (the margin) will be applied to the element. Different widths will have different margin: auto
values.

truongmleon
- 75
- 11
-
@lunatic. Yeah you are right, the other answer talking about block-level elements is correct as there is a default width. – truongmleon Sep 01 '22 at 16:53