Trick: center an absolute position div

In CSS sometimes we complicate our lives with simple things that are less complicated than we think, and that when we see the solution we almost laugh at observing such anecdotes.

More than one person has asked me how to center an absolutely positioned div, and the answer is very simple:

  1. We give the div a fixed width. Example: 500px
  2. We absolutely position the div with 50% left. Example: position: absolute; left: 50%;
  3. We subtract half of what it measures with the margin. Example: margin-left: -250px;

The result is a perfectly centered, absolutely positioned div.


Leave a Comment

Your email address will not be published. Required fields are marked with *

*

*

  1. Responsible for the data: Miguel Ángel Gatón
  2. Purpose of the data: Control SPAM, comment management.
  3. Legitimation: Your consent
  4. Communication of the data: The data will not be communicated to third parties except by legal obligation.
  5. Data storage: Database hosted by Occentus Networks (EU)
  6. Rights: At any time you can limit, recover and delete your information.

  1.   Ivan Lira said

    Thank you very much .. as you say something so simple and that despite the passage of time is still the author of many headaches.
    Your post was very useful to me, thank you very much.

  2.   pod said

    Thank you very much !!!

  3.   glbroman said

    Good contribution helped me a lot, thanks

  4.   LUCASG said

    What a great crazy he served me: D

  5.   Victor said

    Excellent thanks…

  6.   benjamin said

    Very good Carlos.

  7.   Mario Lozano said

    Excellent info

  8.   Frank Koq said

    Thank you, it served me

  9.   marc said

    You saved me!!! Thank you :)

  10.   Danielfloyd said

    Thank you uncle, you helped me a lot !!, that lack of imagination of mine.

  11.   damian said

    thank you very much !!!!! this trick always helps me haha

  12.   o said

    thank you very much excellent friend

  13.   Chrismart Anji said

    This is not centered, it all depends on the original size of the base div element that we make it grow depending on what is put inside it, for me it was more useful to use this than visually if I see it even more centered and reponsive:

    absolutely;
    left: 50%
    margin-left: -100px;

    that would be half.

  14.   Edgar cjuno said

    The contribution is appreciated, it really helped me, greetings!

  15.   Miriam Jess said

    Very good contribution helped me a lot, a thousand grace!