robmisio
robmisio

Reputation: 1176

How to horizontally center fixed content within absolutely positioned parent?

I'm displaying a modal in my app and it's positioned as fixed within an absolutely positioned container that takes up the whole window.

Something like this:

<div>
  <div class="modalWrap">
    <div class="modalContent">
      howdy slick willy
    </div>
  </div>
</div>

.modalWrap {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  background-color: pink;
}

.modalContent {
  width: 150px;
  background-color: white;
  border: 1px solid black;
  padding: 15px;
  position: fixed;
  top: 50px;
  left: 50%;
  transform: translateX(-50%);
}

https://jsfiddle.net/513m6kte/3/

It works when the container is set to take up the whole window width (right: 0). But, I have a use-case where a chat window may come in from the right, so I'll need the container to not take up the whole width. This is easily accomplished by setting the right on the container to 250px, but the modal content then is no longer centered.

How can i make the modal remain centered within the .modalWrap as the width on its container changes?

Upvotes: 0

Views: 37

Answers (2)

HighHopes
HighHopes

Reputation: 2112

Here is the ultimate guide for centering that I have used very much: https://css-tricks.com/centering-css-complete-guide/

This goes through all the options for centering in a Q&A format.

Upvotes: 1

cssyphus
cssyphus

Reputation: 40086

There is an even easier solution, using flexbox.

Flexbox is relatively new, but is hugely useful - and quite easy. There is a reason why the core change from Bootstrap3 to Bootstrap4 is moving from aligning with floats to using Flexbox. In fact, they re-designed the entire Bootstrap grid system - the core of Bootstrap - around flexbox.

By adding these two lines to the parent div:

display:flex;
justify-content:center;

and removing these two lines from the child div (modal content):

xxxleft: 50%;
xxxtransform: translateX(-50%);

The modal will self-adjust, and always remain centered.

Updated jsFiddle Demo


References:

Excellent, fast-paced 5-min Flexbox Tutorial

Best Ever Flexbox Cheat Sheet

Upvotes: 1

Related Questions