Languages
[Edit]
EN

CSS - center element horizontally

0 points
Created by:
Kevin
797

In this article, we would like to show you how to center element horizontally using CSS.

Quick solution:

 

1. Flex layout with center property value

Edit

This aproach uses properties that alows to center child elements.

Note: main advantages of this approach are:

  • no additional properties are needed,
  • it can be used to center text or inline element in easy way. 

2. Automatic margin

Edit

This approach uses fact, the automatic margin on X-axis centers element inside cointainer.

Note: main advantage of this approach is we don't need to set element size.

3. Absolute position with translation

Edit

This approach sets left corner position of internal element in the middle of container and shifts half of element size with relative negative translation.

Note: main advantage of this approach is that it's working when size of element is not set as fixed.   

4. Absolute position with automatic margin

Edit

This aproach is based on combination of three styles:

  • stretch absolute element inside container,
  • automatic margin to center element inside container,
  • fixed width to limit maximal element stretching size. 

Note: main disadvantage of this approach is the requirement to set fixed element size.

 

See also

Edit
  1. CSS - center element vertically

  2. CSS - center element horizontally and vertically

References

Edit
  1. margin - CSS: Cascading Style Sheets | MDN
  2. flex - CSS: Cascading Style Sheets | MDN
  3. position - CSS: Cascading Style Sheets | MDN
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join