水平和垂直对齐div中的图像

时间:2014-10-23 11:35:26

标签: javascript jquery html css twitter-bootstrap

我使用的是Bootstrap和WordPress。

我一直在研究如何在div中水平和垂直对齐图像(显然是经典问题)。我使用这个问题的答案垂直对齐我的图像:How to vertically align an image inside div

现在我需要水平对齐它。我知道这样做,你通常会添加 margin:0 auto;

问题是我所遵循的方法使用 margin:auto; ,如果我将其更改为 margin:0 auto;

我开始制作问题的JSFiddle,但我无法复制它。所以我认为Bootstrap中有一些东西覆盖了它,但我不确定是什么。

以下是我在其他stackoverflow问题上使用垂直对齐解决方案的基本代码:

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;
}

您可以在http://ucaftercruz.com/upcoming/?page_id=30看到问题。它位于顶部的滑块,问题出在.carousel-inner div中。将浏览器的大小调整为大约800px宽,以便能够真正看到问题。

提前非常感谢!

2 个答案:

答案 0 :(得分:2)

我查看了您的网页。如果您只是从此选择器中删除宽度规则,我认为该问题可以自行解决:

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

改为使用

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

答案 1 :(得分:-1)

试试这个

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