Home > Software design >  How to vertically align image inside a div like I do with margin auto?
How to vertically align image inside a div like I do with margin auto?

Time:07-11

I have this card I am trying to make, that has an image container, and inside the image. With the display: block on the image which you can see below, I am able to get an even space on the left and right side for the image.

I was wondering how I vertically align the image, similar to margin: auto so that from top and bottom i also get the space evenly distributed to center the image?

.img-container {
   border: 1px solid black;
   width: 170px;
   margin: auto;
   border-radius: 10px;
   height: 180px;
}

.card img {
    max-width: 130px;
    display: block;
    margin: auto;
}

enter image description here

CodePudding user response:

The <img> is display: "any value but inline or none" and add this to the container:

  display: flex;
  justify-content: center; /* Center children tags horizontally */
  align-items: center;     /* Center children tags vertically */

main {
  display: flex;
}

figure {
  display: flex;
  justify-content: center;
  align-items: center;
  outline: 3px dashed red;
  width: 32vw;
  height: 84vh;
  padding: 10px
}

img {
  display: block;
  width: 80%;
}
<main>
  <figure>
    <img src='https://loremflickr.com/320/270'>
  </figure>

  <figure>
    <img src='https://loremflickr.com/80/45'>
  </figure>

  <figure>
    <img src='https://loremflickr.com/160/90'>
  </figure>
</main>

CodePudding user response:

you can use it this way, add a relative position in the parent, and absolute position in the child, then adjust the position of the card using transform.

.img-container{
width: 170px;
border: 1px solid black;
margin: auto;
border-radius: 8px;
height: 180px;
position: relative;}

.card img{
max-width: 130px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
margin: auto;}


<div >
    <div >
        <img src="https://images.unsplash.com/photo-1657477267946-b433c0edbec9?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1170&q=80" alt="">
    </div>
  • Related