Recently I needed to do something relatively simple (or it should be): Ensure that a popup box (modal) opened in the center of a website. I’ve been bad about saving or bookmarking my favorite CSS rules for doing things like this which is why I’m taking a moment to log this now.
In the past, I might do something related to ensuring there was a container div, and I’d do the position: relative, margin: 0 auto, trick. But, thanks to this, I’ve discovered the following way. Which so far, seems to work really well and it’s much easier. You target the modal directly.
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 50%;
}
This will also be easy to remember because I can think of it as the fixed, 50% transform trick.
Leave a Reply