我在 div 中有一个 div 和一个图像。图像大小会有所不同。
我希望它水平和垂直居中。Css 垂直对齐似乎不起作用。
有什么技巧吗?我可以使用 php、css 或 Jquery
我在 div 中有一个 div 和一个图像。图像大小会有所不同。
我希望它水平和垂直居中。Css 垂直对齐似乎不起作用。
有什么技巧吗?我可以使用 php、css 或 Jquery
您可以通过使用使其水平对齐
margin: 0 auto;
使用CSS垂直居中并不容易(至少在 IE6/7 中不是)。使用表格相对容易。
你说你有 jQuery 可用。您可以通过应用 JavaScript 来启动任何浏览器。当然,如果没有启用/支持 JS,您的页面将无法正确显示。
CSS 的 vertical-align 属性仅适用于 with display: table-cell
(它本身应该在 with 中display: table
)。
如果你有
<div id="container"><img src="my-image.png" alt="" /></div>
您可以像这样使用 jQuery 将其居中(如plexus的建议)
var imageSrc = $('#container img').attr('src');
$('#container').css({ backgroundImage: 'url(' + imageSrc + ')', backgroundPosition: 'center enter' });
我不知道你如何使用它,所以我的解决方案可能不适合。
当您在 div 中将图像实现为“背景图像”时,您可以轻松地将其与“背景位置”居中:
#div {
background-image: url(./image.png);
background-position: center center;
}
<style>
.image-container {
position:relative;
width:300px;
height:300px;
background:#ccc;
}
.image-container .image {
position:absolute;
top:50%;
left:50%;
transform:translate(-50%, -50%);
background:red;
height:100px;
width:100px;
}
</style>
<div class="image-container">
<img class="image" src="****.jpg"/>
</div>