我已经尝试了很多来自 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/