There are multiple possible solutions
Many times you will have to horizontally center a element in another one but depending on the case, this problem can have different solutions.
The most common one is the one presented in the working example below, where both elements have an width and you can simply center them by adding margin-left: auto
and margin-right: auto
, this will take the remaining space and not occupied by your inner element and divide it left and right of this element. This will result in your inner element being centered.
The other way to do this is if your parent element has position: relative
and your child element has position: absolute
then you can center the inner element by positioning him left: 50%
and making a margin-left
of half the inner element`s width. Why? well without it your inner element will start at half of the width of the outer element and by adding the negative margin-left
your inner elements center will be align with your outer element's center. here is an example:
#outer { position: relative; }
#inner { position: absolute; width: 200px; left: 50%; margin-left: -100px; }
Another way is by text-align: center
the outer element and adding display: inline-block
to the inner element.
#outer { width: 100%; text-align: center; }
#inner { display: inline-block; }
Try them out below see which suits you best 🙂
- html
- css