Search code examples
htmlcssmaterialize

Center an Image Vertically inside a div in Materialize CSS


I am trying to align images vertical inside card in Materialize. I have also use a custom slider called xlider inside the card. The images are horizontally centered, but not vertically.

.custom{
  width: 350px;  /*Used in (1), This is done so the column doesn't change shapes through out any screen*/
}

.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 40%;
  width: auto;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  user-select: none;
    background-color: rgba(0,0,0,0.8);
  display: none;
}

/* Position the "next button" to the right */
.next {
 right:0;
}

@media (hover: hover){
.card:hover .prev,
.card:hover .next{
  display: block;
}
}

.xlider {
  width: inherit;
  height: inherit;
  display: flex;
  overflow-x: auto;
  overflow-y: hidden;
  -webkit-overflow-scrolling: touch;

}
::-webkit-scrollbar {
  display: none;
}
.xlide {
  width: 100%;
  flex-shrink: 0;
  height: inherit;
  overflow:hidden;
}
.xlide img {
margin:auto;
position: absolute;
object-fit: contain;
max-height:100%;
align-items: center;
}

    <div class="col custom">
        <div class="card" >
            <div class="card-image grey lighten-3" style="height: 245px; position: relative;overflow: hidden; ">
              <div class="xlider">    
                 <div class="xlide"><img src="https://images.craigslist.org/00505_dRUnpYQSFVu_300x300.jpg" ></div>
                 <div class="xlide"><img src="https://images.craigslist.org/00s0s_eCSJ00mPdFU_300x300.jpg" ></div>
                 <div class="xlide"><img src="https://images.craigslist.org/00p0p_6neNmaCByuU_300x300.jpg" ></div>
                 <div class="xlide"><img src="https://images.craigslist.org/00n0n_8uRrQ143Bdz_300x300.jpg" ></div>
                 <div class="xlide"><img src="https://images.craigslist.org/00J0J_bd1qKahXbwH_300x300.jpg" ></div>

              </div>
              <a class="prev" onclick="goLeft(this)">&#10094;</a>
              <a class="next" onclick="goRight(this)">&#10095;</a>

            </div>

        </div>
    </div>

I have tried putting verticle-align, align-item, margin-top. and so far all of these have failed.

A live version of the code is here:

https://jsbin.com/mapesidasu/edit?html,output


Solution

  • I just Make some changes to your CSS. try this :

    .xlider {
      width: inherit;
      height: inherit;
      display: flex;
      overflow-x: auto;
      overflow-y: hidden;
      -webkit-overflow-scrolling: touch;
    }
    
    .xlide img {
    object-fit: contain;
    height:100%;
    align-items: center;
    }