Thomas Kowalski
Thomas Kowalski

Reputation: 2184

Center vertically a modal div which is not always the same height?

So i've got a modal div (set with z-index) that I'm trying to center vertically. The thing is I use it for not only one content but several ones, so the height is not fix. And while having a general "fix" (I'll explain in just after) of -150px in the margin-top generally works for short content, when having a lot of content, the div will start at mid-page and finish at the end (which is not what I want at all). Here is my code :

.modal
{
    padding: 10px;
    border: 1px black solid;
    width: 80%;
    position: absolute;
    background: white;
    left: 50%;
    top: 50%;
    margin-top: -150px;
    margin-left: -40%;
    z-index: 1000;
    border-radius: 5px; 
    max-height: 80%;
    overflow: scroll;
}

So here you can see the "fix". It works kind of well when the content is short :

Short content

It's pretty ugly when the content is big :

Large content

Does anyone have an idea of how to fix that ?

Thank you in advance

Upvotes: 0

Views: 96

Answers (3)

Nitekurs
Nitekurs

Reputation: 451

.modal{
    padding: 10px;
    border: 1px black solid;
    width: 80%;       
    background: white;        
    z-index: 1000;
    border-radius: 5px; 
    max-height: 80%;
    overflow: scroll;
    position: absolute;
    left:0;
    top:0;
    right:0;
    bottom:0;
    margin: auto;
}

Upvotes: 0

fcastillo
fcastillo

Reputation: 948

You could use this. Top 50% position the div on the 50% of the container y translate -50% is referred to his height and no the container:

.modal {
  padding: 10px;
  border: 1px black solid;
  width: 80%;
  position: absolute;
  background: white;
  left: 50%;
  margin-left: -40%;
  z-index: 1000;
  border-radius: 5px; 
  max-height: 80%;
  overflow: scroll;
  top: 50%;
  transform: translateY(-50%);
  -o-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
}

FIDDLE

Upvotes: 3

ShahiM
ShahiM

Reputation: 3268

Add the following css to center the div. note that this only works on position:absolute elements.

  top: 0;
  bottom:0;
  margin-top: auto;
  margin-bottom: auto;

So your css will become:

.modal
{
  padding: 10px;
  border: 1px black solid;
  width: 80%;
  position: absolute;
  background: white;
  left: 50%;
  top: 0;
  bottom:0;
  margin-top: auto;
  margin-bottom: auto;
  margin-left: -40%;
  z-index: 1000;
  border-radius: 5px; 
  max-height: 80%;
  overflow: scroll;
}

Upvotes: 0

Related Questions