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

标签 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/ 中的测试用例

最佳答案

我的建议是添加一个围绕 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
}

关于html - CSS 在 img 标签中水平和垂直居中图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22849385/

相关文章:

css - 尝试为 Wordpress 站点 Logo 添加样式

javascript - 使用 rowspan 调整表的大小

php - 单击链接更改语言

html - 图片 Alt 标签/标题默认左对齐。我怎样才能改变到中心

javascript - 使用 JavaScript 写入 HTML

javascript - 通过鼠标按下(拖动)输入更改值在 Chrome 中不起作用

css - 在 SASS 中,在嵌套结构中使用后置选择器 & 号不起作用

c# - 如何使文本在网络表单上居中?

html - CSS动态移动div到圆心

html - 自动高度外部div