Tuesday, February 19, 2019

Center image in HTML DIV horizontally

First Part is the CSS

Somebody once said "I have an img in a div and I want this image to be exactly in the middle of the div but nothing I try works..."
Suppose you want to place 2 images side by side and centered in their div elements. you need to edit your style sheets to have an outer div, and 2 inner divs, and an image element inside the inner divs. You need to set your margin sides to auto, and your width to 50%

  1. div.column-2-block { position:relative; float: left; display:inline-block; border: 0px red solid; margin-top:25px; } div.column-inside { position:relative; float: left; display:inline-block; border: 0px green solid; width:50%; } div.image-holder { position:relative; display:block; }
  2. // THIS CSS WILL MAKE IT CENTERED img.centered { margin:0 auto; width:50%; }

Then the HTML code
  1. <div class="column-2-block"> <div class="column-inside"> <img class="centered" src="https://cdn.shopify.com/s/files/SOS.png" width="320"> </div> <div class="column-inside"> <img class="centered" src="https://cdn.shopify.com/s/files/watch.jpg" width="400"> </div> </div>

The Result

No comments:

Post a Comment