Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There's a way to centre variable width block elements that doesn't depend on flexbox, which is:

    .centred {
        /* Make the element only as wide as it needs to be. */
        display: inline-block;
        /* Let us apply positioning. */
        position: relative;
        /* Move the left of the element to the middle of the container. */
        left: 50%;
        /* Translate backwards half the width of the block, thus centring it. */
        transform: translateX(-50%);
    }
It's a useful bit of CSS to have around.


I use a similar trick all the time, especially for vertically centering elements. Also, mine usually includes the various vendor prefixes for the browsers.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: