Home > front end >  Positioning a modal, with support to scrollbars, correctly
Positioning a modal, with support to scrollbars, correctly

Time:10-20

I need a modal, positioned at the center, with support to dynamic content height and with support to scrollbars in case the content height is greater than the screen.

Here's my attempt:

#outer {
  position: fixed;
  margin: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100vh - 80px);
  height: 100%;
}

#inner {
  background-color: #0000FF;
  color: #FFF;
  padding: 10px;
  height: 100%;
  overflow: auto;
}

.content-item {
    margin-bottom: 50px;
}
<html>
  <body>
    <div id="outer">
      <div id="inner">
        <div  style="background-color: red">My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div >My Content</div>
        <div  style="background-color: yellow">My Content</div>
      </div>
    </div>
  </body>
</html>

The problem is... if content is not greater than screen, it will occuppy full height (try leaving only the first and last .content div.

CodePudding user response:

Here's the solution:

#outer {
  position: fixed;
  margin: auto;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100%;
  height: 100%;
}
#inner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-height: calc(100% - 80px);
  padding: 10px;
  background-color: #0000FF;
  color: #FFF;
  overflow-y: scroll;
}
.content-item {
    margin-bottom: 50px;
}
<div id="outer">
  <div id="inner">
    <div  style="background-color: red">My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div >My Content</div>
    <div  style="background-color: yellow">My Content</div>
  </div>
</div>

  •  Tags:  
  • css
  • Related