Search code examples
htmlcssmaterialize

How to vertically and horizontally center image inside a div?


I'm using Materialize CSS, fail to vertically and horizontally center a image inside a div, margin: 0 auto doesn't work at all.

.blockA {
  border: 1px solid black;
}

.imgA {
  border: 1px solid red;
  margin: 0 auto;
  width: 100px;
}

.textA {
  border: 1px solid blue;
}
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" />
    <div class="container">
      <div class="row blockA">
        <img class="imgA" src="http://via.placeholder.com/350x150">
        <p class="textA center-align">
          TEXT
        </p>

      </div>
    </div>

Please help!


Solution

  • There are 2 ways to achieve what you want if I understand your goal correctly:

    1. Wrap your image with a new div and assign these styles to it:
    .image-wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    

    But in this case, you won't have any paddings inside the image wrapper, so it will stick to its edges.

    1. Again, wrap the image with a div, and assign this:
    .image-wrapper {
      padding: 1em;
      text-align: center;
    }
    

    margin: 0 auto doesn't work with the image, since it's an inline element. You can align inline elements with text-align property. But you can make a block element from an inline one by applying display: block to it.

    Hope that helps!