Frederik Sohnis
Frederik Sohnis

Reputation: 1095

How can you center a div within a div with overflow hidden?

Is there any way to get a child div to center itself within a parent div with hidden overflow and ignore the hidden overflow?

Example:

.outer {
  width: 100%;
  margin-left: 40px; /*will cause overflow*/
  overflow-x: hidden;
}
.inner {
  width: 80px;
  height: auto;
  margin: 0 auto;
  position: relative;
}
<div class="outer">
  <div class="inner">
  Hello World
  </div>
</div>

Expected Output:

----------------------------------////
| outer                          |   / <- Hidden overflow
|                                |   /
|            --------            |   /
|            |inner |            |  <- Centered
|            --------            |   /
|                                |   /
----------------------------------////

Actual Output:

----------------------------------////
| outer                          |   / <- Hidden overflow
|                                |   /
|                --------        |   /
|                |inner |        | <- not centered
|                --------        |   /
|                                |   /
----------------------------------////

If outer div didn't have overflow, the inner div should be centered horizontally but because of overflow. The inner div will be slightly off center. Is there anyway to get the inner div to not center itself with in the visible part of the outer div?

EDIT:

This question is not a duplicate. The suggested duplicate is how to center a div in another, given that there is no hidden overflow. My question is specific to centering a div within a parent div with a width that overflows and is hidden. In such a scenario the linked to proposed duplicate does not supply a satisfactory solution.

Upvotes: 0

Views: 854

Answers (1)

Liam
Liam

Reputation: 6743

I guess I understand what are you trying to do.

you can accomplish that by using fixed position and if you want to make it above all elements you can use z-index

Example

.outer-container {
  display: table;
  width: 120%;
  height: 120px;
  background: #ccc;
  overflow: hidden;
}

.inner-container {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.centered-content {
    display: inline-block;
    background: #fff;
    padding: 20px;
    left: 50%;
    top: 50%;
    transform: translate3d(-50%,-50%,0);
    z-index: 100;
    position: fixed;
    border: 1px solid;
}
<div class="outer-container">
  <div class="inner-container">
    <div class="centered-content">
      overflow: hidden
    </div>
  </div>
</div>

Upvotes: 1

Related Questions