DJONES DJONES - 5 months ago 13
CSS Question

CSS - center and rounded Img Inside Div

I have an Img inside a Div on my webpage, the image appears inside the div, but the alignment is off depending on the browser width.

this is my code:

<div class="w3-row" style="100%; background-color: #fff; margin-top: 5px; height: 100px; padding: 5px;">
<div class="w3-col w3-container w3-green" style="width: 15%; height: 100%;">
<div>
<img class="" src="../images/Joanne.jpg" alt="Chania" style="height: 80px; display: block; margin-left: auto; margin-right: auto;">
</div>
</div>
<div class="w3-col w3-container w3-red" style="width: 85%; height: 100%;">

</div>
</div>


this is the Image I am using:
http://s33.postimg.org/vnc0xbztb/Joanne.jpg

I was wondering if there was a way I could vertically and horizontally align the Image inside that Div, and maybe also have the image with rounded corners.

I have searched around but nothing I try works, I thought by setting the margin left and right to 'auto' would solve my problem, but the image is still off when I resize the browser.

Any help or advice is appreciated.

Answer

For a rounded image - use the border-radius property

For a vertically centered image - Use display:flex and align-items:center on the parent element of the image that has a specified height.

It should look like this:

.image {
  border-radius: 50px;
}
.w3-col.w3-container.w3-green {
  display: flex;
  align-items: center;
}
.w3-row {
  border: 1px solid #aaa;
}
<div class="w3-row" style="100%; background-color: #fff; margin-top: 5px; height: 100px; padding: 5px;">
  <div class="w3-col w3-container w3-green" style="width: 15%; height: 100%;">
    <div>
      <img class="image" src="http://s33.postimg.org/vnc0xbztb/Joanne.jpg

" alt="Chania" style="height: 80px; display: block;  margin-left: auto;  margin-right: auto;">
    </div>
  </div>
  <div class="w3-col w3-container w3-red" style="width: 85%; height: 100%;">

  </div>
</div>

I added the 1px border property for clarity.