将流体图像在流体容器中垂直居中
我当然不想添加到一堆垂直对齐 CSS 问题中,但我花了几个小时试图找到解决方案,但仍无济于事。情况是这样的:
我正在构建一个图像幻灯片库。我希望图像显示得与用户窗口允许的一样大。所以我有这个外部占位符:(
<section class="photo full">
是的,我正在使用 HTML5 元素)。其中具有以下 CSS:
section.photo.full {
display:inline-block;
width:100%;
height:100%;
position:absolute;
overflow:hidden;
text-align:center;
}
接下来,将图像放置在其中。根据图像的方向,我将宽度或高度设置为 75%,将另一个轴设置为自动:
$wide = $bigimage['width'] >= $bigimage['height'] ? true: false; ?>
<img src="<?= $bigimage['url'] ?>" width="<?= $wide? "75%" : "auto"?>" height="<?= $wide? "auto" : "75%"?>"/>
因此,我们有一个流体外部容器,内部有流体图像。图像的水平居中有效,但我似乎无法找到一种方法将图像在其容器内垂直居中。我研究了居中方法,但大多数假设容器或图像具有已知的宽度或高度。然后是 display:table-cell 方法,它似乎也不适合我。
我被困住了。我正在寻找 CSS 解决方案,但我也对 js 解决方案持开放态度。
I certainly do not want to add to the pile of vertical alignments CSS questions, but I've spent hours trying to find a solution to no avail yet. Here's the situation:
I am building a slideshow gallery of images. I want the images to be displayed as large as the user's window allows. So I have this outer placeholder:
<section class="photo full">
(Yes, I'm using HTML5 elements). Which has the following CSS:
section.photo.full {
display:inline-block;
width:100%;
height:100%;
position:absolute;
overflow:hidden;
text-align:center;
}
Next, the image is placed inside it. Depending on the orientation of the image, I set either the width or height to 75%, and the other axis to auto:
$wide = $bigimage['width'] >= $bigimage['height'] ? true: false; ?>
<img src="<?= $bigimage['url'] ?>" width="<?= $wide? "75%" : "auto"?>" height="<?= $wide? "auto" : "75%"?>"/>
So, we have a fluid outer container, with inside a fluid image. The horizontal centering of the image works, yet I cannot seem to find a way to vertically center the image within it's container. I have researched centering methods but most assume either the container or image has a known width or height. Then there is the display:table-cell method, which does not seem to work for me either.
I'm stuck. I'm looking for a CSS solution, but am open to js solutions too.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这很好:
我猜显示表格单元格不适合你,因为它的父容器没有显示为表格。
这是 jsfiddle 中的演示:
http://jsfiddle.net/duopixel/5wzPS/
This works out fine:
I'm guessing display table-cell hadn't worked for you because it's parent container wasn't displayed as a table.
Here is a demo in jsfiddle:
http://jsfiddle.net/duopixel/5wzPS/
也许这对你有用(
div
是围绕你的图像的 div):运行示例。
Maybe this works for you (
div
is the div wrapped around your image):Running example.
让我们跳过所有餐桌上的废话吧! :)
示例: https://jsfiddle.net/te29m9fv/1/
Let's skip all of the table nonsense! :)
Example: https://jsfiddle.net/te29m9fv/1/