Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to center image

I’d like to use flexbox to center the image. Can I do this without putting the picture in another div?

I think I tried all flexbox options but not sure, that’s why I’m asking.

Here’s some HTML and CSS code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  body {
  font-family: sans-serif;
  font-size: 10vw;
  display: flex;
  flex-direction: column;
  background-color: grey;
  word-wrap: break-word;
}

p {
  text-indent: 5vw;
}

p.Intro {
  /* See other colors @ media queries */
}

Img.MainIMG {
  max-height: 50vh;
  max-width: 50vw;
  display: flex;
  align-items: center;
  justify-content: center;
<main>

  <H1>Hi!</H1>
  <p class="Intro">
    Lorem ipsum dolor sit amet.
  </p>
  <p class="Intro">
    Sed ut perspiciatis unde omnis iste natus error.
  </p>
  <p class="Intro">
    Lorem ipsum dolor sit amet.</p>

  <img src="https://images.unsplash.com/photo-1530995377270-ac41692cd439?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzUwNzQzNDE&ixlib=rb-4.0.3&q=80" class="MainIMG" alt="Smiling person">

  <H1>Goodbye!</H1>
</main>

>Solution :

transfer the image to a block-level element with display: block. Block level elements can be centered with margin: 0 auto:

body {
  font-family: sans-serif;
  font-size: 10vw;
  display: flex;
  flex-direction: column;
  background-color: grey;
  word-wrap: break-word;
}

p {
  text-indent: 5vw;
}

p.Intro {
  /* See other colors @ media queries */
}

Img.MainIMG {
  max-height: 50vh;
  max-width: 50vw;
  display: block;
  margin: 0 auto;
}
<main>

  <H1>Hi!</H1>
  <p class="Intro">
    Lorem ipsum dolor sit amet.
  </p>
  <p class="Intro">
    Sed ut perspiciatis unde omnis iste natus error.
  </p>
  <p class="Intro">
    Lorem ipsum dolor sit amet.</p>

  <img src="https://images.unsplash.com/photo-1530995377270-ac41692cd439?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NzUwNzQzNDE&ixlib=rb-4.0.3&q=80" class="MainIMG" alt="Smiling person">

  <H1>Goodbye!</H1>
</main>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading