Can't center react component on the screen

Viewed 1557

I have a modal window, which opens on the click of the user. I am trying to center it and use standard CSS code:

.layout: {
    position: "absolute";
    left: "50%";
    top: "50%";
}

But it centers element inside its parent, and I don't know why, because a parent has static position (so absolute should count from the edge of the screen, not a parent). How to fix it? Here is the structure of a modal window:

<div class="layout">
    <div class="window">
        <!--some code --!>
    </div>
</div>
3 Answers

If you want to center it on whole screen then position fixed will be the choice for you, and don't use hardcoded pixels to center it, istead use Transform property, Like this

.layout {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); 
}

and if you want to center it in some section or div, then use position absolute,

.layout {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); 
}

But in absolute condition, give position: relative to its parent.

if you will use transform: translate(-50%, -50%); you will never need to worry about the height or width of your item, in hardcoded pixels, if your element's height and width will increase or decrease, then your alignment of the item will distort.

check the example below with position fixed,

.layout {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); 
}
<div class="layout">
    <div class="window">
        <!--some code --!>
        ABC
    </div>
</div>

In this case, if you use absolute or fixed positioning, you need to set negative margins of half width and height of your element you need to center. if you want to set you element related the whole screen it better use position 'fixed'

.element {
    width: 300px;
    height: 300px;
    position: fixed;
    top: 50%;
    left: 50%;
    margin-left: -150px;
    margin-top: -150px;
}

if you need more flexible solution, when you don't know popup's size, use transform: translate(-50%, -50%); instead of margins.

but better solution will be use flexboxes trhttps://alligator.io/css/centering-using-flexbox/

The CSS position: absolute attribute positions it relative to the nearest positioned parent node. If you want to position your element relative to the viewport, you should use position: fixed.

You can find more info about the options for this property here.

Related