Centered div larger than its container overflow scroll

家住魔仙堡 提交于 2019-12-25 01:03:02

问题


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:


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>


来源:https://stackoverflow.com/questions/48787324/centered-div-larger-than-its-container-overflow-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!