Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this CSS code to center an element work?

Tags:

css

    position: absolute;
    top: 50%;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)

This is CSS code for centering a button in the viewport. Can somebody explain how this works? I found it somewhere online and it seems to work but I don't get the need for margin-right and transform. Naturally the code doesn't work without them but intuitively I feel the first three should be enough to center the element. I'm relatively new to CSS so I'd understand if this is considered a silly question :)

like image 370
Sanchit Batra Avatar asked Jul 14 '26 10:07

Sanchit Batra


1 Answers

Take a look at this article: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/. Simply using the first three lines of css (position, top, and left) will center the top left corner of the object, which will make the whole object completely off-center. The negative translation moves the object up and to the right by half of its height and width, respectively, which makes the object centered. In fact, I don't think you even need the margin-right code, but I might be wrong.

like image 119
Anthony C Avatar answered Jul 28 '26 20:07

Anthony C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!