Tara
Tara

Reputation: 261

Horizontally and vertically align image in div

I'm using Bootstrap and WordPress.

I've been researching how to horizontally and vertically align an image inside a div (classic problem, apparently). I used the answer to this question to vertically align my image: How to vertically align an image inside div

Now I need to horizontally align it. I know to do that, you normally add margin: 0 auto;

The problem is that the method that I followed uses margin:auto; and it undos the vertical align if I change it to margin:0 auto;

I started to make a JSFiddle of the problem, but I couldn't replicate it. So I think it's something in Bootstrap that is overriding it, but I'm not sure what.

Here is the basic code I'm using from the vertical align solution on the other stackoverflow question:

HTML

<div class="crop-featured-2">
    <img src="image.png">
</div>

CSS

.container { 
     position: relative;
     width: 100%;
     overflow: hidden; 
}

.crop-featured-2 {  
    height: 100px;
    width: 200px;
    position: relative;
    border: 1px solid red;
    padding: 5px;
    display:block;
}  
.crop-featured-2 img {  
    min-height: 100px;  
    width:100%;
    position: absolute;  
    top: 0;  
    bottom: 0;  
    left: 0;  
    right: 0;  
    margin: auto; 
    border:0px; 
    padding:0;
}

You can see the problem at http://ucaftercruz.com/upcoming/?page_id=30. It's the slider at the top and the problem is in the .carousel-inner div. Resize the browser to around 800px wide to be able to really see the issue.

Thanks so much in advance!

Upvotes: 0

Views: 140

Answers (2)

Nitish Kumar
Nitish Kumar

Reputation: 316

Try this

.crop-featured-2 {
position: relative; 
margin: 0;
position: absolute;
top: 50%;
left: 50%;
margin-right: -50%;
transform: translate(-50%, -50%);
}

Upvotes: -1

Albin
Albin

Reputation: 3012

I had a look at your web page. I think the issue solves it self if you just remove the width rule from this selector:

.crop-featured-2 { 
  height: 320px;
  width: 575px;
  position: relative;
}

instead use

.crop-featured-2 { 
  height: 320px;
  position: relative;
}

Upvotes: 2

Related Questions