如何将 div 内的图像与动态高度垂直对齐?
我们有一个 div,其中包含用户上传的图像。代码如下:
HTML:
<div class="container_img">
<img height="120" width="150" src="[image name].jpg">
</div>
CSS:
div.container_img {
overflow: hidden;
width: 150px;
height: 150px;
}
我们的问题是,如果用户上传的图片高度小于 150px,底部就会有很大的空间。所以我们想要垂直对齐图像,这样它看起来就不像是浮动的。
我尝试在网上寻找解决方案,但找不到适用于 DIV 内动态图像的解决方案。某些解决方案要求您知道图像的尺寸。
有人遇到过这个问题并解决了吗?
What we have is a div that contains an image that a user uploads. This is the code:
HTML:
<div class="container_img">
<img height="120" width="150" src="[image name].jpg">
</div>
CSS:
div.container_img {
overflow: hidden;
width: 150px;
height: 150px;
}
Our problem is if the image the user uploads has a height smaller than 150px, there's a big space at the bottom. So we want to vertically align the image so that it doesn't look like it's just floating.
I've tried searching for solutions on the net but I can't find one that works with dynamic images inside a DIV. Some solutions require that you know the dimensions of the image.
Has anybody had this problem and solved it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您需要使用 JavaScript/jQuery 来检测图像高度。 CSS 不是动态语言,您无法使用纯 CSS 检测高度。使用 jQuery,您可以执行
jQuery
CSS
检查工作示例,网址为 http ://jsfiddle.net/nQ4uu/2/
You need to use JavaScript/jQuery to detect image height. CSS is not a dynamic language and you cannot detect height using pure css. Using jQuery you can do
jQuery
CSS
Check working example at http://jsfiddle.net/nQ4uu/2/
有效,但我不确定它是否适用于所有 IE 版本。
works but I'm not sure if it does on all IE versions.
我认为您无法使用任何直接的技术垂直对齐图像。您可以看到 this 用于水平对齐图像...
I think you won't be able to align the image vertically using any straight forward technique. You can see this for aligning the image horizontally though...
这并不容易,请查看此页面 http://www.vdotmedia.com /demo/css-vertically-center.html
it is not that easy, check out this page http://www.vdotmedia.com/demo/css-vertically-center.html
您可以在 css 中使用 flex 来实现这一点:
You can achieve this using flex in css:
就有更好的答案
我知道这是一个老问题,但我认为仅使用 CSS演示 jsFiddle
HTML
CSS
就是这样!
I know this is an old question but i think there i s abetter answer with CSS alone
DEMO jsFiddle
HTML
CSS
That's it!