Centered div larger than its container overflow sc

2019-08-23 23:33发布

Having an absolutely placed and perfectly centered ("translate trick") div within a container: jsfiddle.

<div id='container'>
  <div id='content'>
    <p>
      centered...
    </p>
  </div>
</div>

#container{
  position: relative;
  width: 400px;
  height: 400px;
  background-color: gray;
}

#content{
  position: absolute;
  width: 100px;
  height: 100px;
  top: 50%;
  left: 50%;
  border: 1px solid red;
  transform: translate(-50%, -50%);
}

Now when this inner div becomes larger than it's container and the container has overflow: auto (scroll). It becomes impossible to get the utmost top and left part of the inner div to become visible within the container by scrolling it to the left and top and its maximum: jsfiddle.

#container{
  ...
  overflow: auto;
}

#content{
  ...
  width: 500px;
  height: 500px;
  ...
}

The "same" thing happens when the inner div is scaled to a proportion that it overflows the container div: jsfiddle.

#container{
  ...
  overflow: auto;
}

#content{
  ...
  transform: ... scale(5);
}

Any ideas on how to have the inner div stay centered and still be able to reach all its area by using the scrollbars of the container div? Or should the "centeredness" be dropped when the size overflows the container (possibly using javascript)? A pure css solution is much preferred.

1条回答
叛逆
2楼-- · 2019-08-24 00:19

You could use some absolute positioning to do the centering, a max-height and max-width, and put the scroll on the inside container, like so:

https://jsfiddle.net/hnzo2sa4/

.container {
  position: relative;
  background-color: gray;
  margin: 10px;
}

.bigger {
  width: 300px;
  height: 300px;
}

.same {
  width: 200px;
  height: 200px;
}

.smaller {
  width: 100px;
  height: 100px;
}

.content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  width: 200px;
  height: 200px;
  max-width: 100%;
  max-height: 100%;
  background: rgba(987, 654, 321, .6);
  overflow: scroll;
}
<div class="container bigger">
  <div class='content'>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
  </div>
</div>

<div class="container same">
  <div class='content'>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
  </div>
</div>

<div class="container smaller">
  <div class='content'>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
    <p>centered...</p>
  </div>
</div>

查看更多
登录 后发表回答