CSS在img标签中水平和垂直居中图像

时间:2014-04-03 21:29:07

标签: html css

我尝试过stackoverflow的许多解决方案。没有适用于我的情况。我想知道我是否仍然可以将图像置于我的html结构限制中心?

这是我的CSS和HTML。

<div class="test">  
    <img src="http://test.com/test.jpg" />
    This is the test text here..This is the test text here.This is the test text here.
</div>

CSS:

div.test {
    width: 300px;
    height: 120px;
    border: solid 1px #CCCCCC;
}

img {
    position: relative;
    top:auto;
    left: auto;
    float: right;
    display:table-cell;
    width:auto;
    height:auto;
    max-width: 100px;
    max-height: 100px;
    vertical-align: middle;
}

以下是http://jsfiddle.net/QBK2y/3/

中的测试用例

3 个答案:

答案 0 :(得分:0)

如果您正在尝试水平居中图像,那么您需要的是:


img {
  display: block;
  margin: 0 auto;
}

答案 1 :(得分:0)

一种在水平和垂直方向上对齐高度设置元素的元素的一种方法..

.test {
    width: 300px;
    height: 120px;
    position:relative;
}

.test img {
  position:absolute; 
  top:0;
  left:0
  bottom:0;
  right:0;
  margin:auto;
}

修改:Forked your fiddle - http://jsfiddle.net/669sW/


现在如何处理该文本......

答案 2 :(得分:0)

我的建议是在img标签周围添加一个div,如下所示。遗憾的是,HTML结构限制无法满足。如果没有占位符,则无法使图像居中。

<div class="test">
    <div class="placeholder">
         <img src="http://test.com/test.jpg" />
    </div>
    This is the test text here..This is the test text here.This is the test text here.
</div>

然后,新的css应该是。

div.test {
    width: 300px;
    height: 120px;
    border: solid 1px #CCCCCC;
}

img {
    position: absolute;
    top:0;
    left: 0;
    right: 0;
    bottom: 0;
    margin:auto;
    display: inline-block;
    width:auto;
    height:auto;
    max-width: 100px;
    max-height: 100px;
}

div.placeholder {
    position: relative;
    top:auto;
    left: auto;
    float: right;
    width: 100px;
    height: 100px;
    border: solid 1px #CCCCCC; //border is not necessary
}