Daniel
Daniel

Reputation: 3711

How to center a div fixed over another?

I am trying to center a div (overlay) over another. I've managed to center it inside the div. But then it will be cut off and not stick to the center when the content of the parent is scrolled. Unfortunately, the overlay cannot just be set to fixed: https://stackoverflow.com/a/20621323/1981832.

Here is my code so far:

https://codepen.io/anon/pen/PjyYwV

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
}
<div class="parent">
  <div class="overlay"></div>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
</div>

Upvotes: 1

Views: 140

Answers (2)

Daniel
Daniel

Reputation: 3711

Found a way to get what I wanted. However, I consider it non-ideal since it needs an additional wrapper element.

.parent {
  position: relative;
  height: 50px;
  width: 200px;
  border: 1px solid blue;
  white-space:nowrap;
  overflow: scroll;
}

.wrapper {
  position: relative;
  display: inline-block;
  border: 1px solid red;
}

.overlay {
  position: absolute;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 100px;
  width: 100px;
  background-color: red;
  z-index: 100;
}
<div class="wrapper">
  <div class="overlay"></div>
  <div class="parent">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  </div>
</div>

Upvotes: 1

Vadim Ovchinnikov
Vadim Ovchinnikov

Reputation: 14032

You can use flexbox for this. Also you'll have to add wrapper that will occupy content's width and height and move text to some tag (i.e. span):

.parent {
  height: 50px;
  max-width: 200px;
  border: 1px solid blue;
  white-space: nowrap;
  overflow: scroll;
}

.flex {
  position: relative;
  display: inline-flex; /* Width fit content */
  min-width: 100%; /* Not less than parent's width */
  min-height: 100%; /* Not less than parent's height */
  justify-content: center; /* Center items horizontally */
  align-items: center;  /* Center items vertically */
}

.overlay {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: red;
}
<div class="parent">
  <div class="flex">
      <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</span>
      <div class="overlay"></div>  
  </div>
</div>

Upvotes: 0

Related Questions