好的,这是我的问题。我有一个 348px 宽的 block ,在右侧 144px,我想将图像垂直居中。容易,对吧?我的问题是我不知道图像或 block 的高度。如何使图像垂直居中以超过容器顶部而不使其成为背景图像?
CSS
#block { width: 348px; position: relative; }
#content { width: 164px; padding: 20px; margin-right: 144px; }
#image { width: 144px; position: absolute; right: 0; }
MARKUP
<div id="block">
<div id="image"><img url="imageurl" /></div>
<div id="content">Some content goes here.</div>
</div>
我不知道这会有多大帮助,但希望它能有所帮助。
最佳答案
仅使用 CSS 的解决方案,基于您当前的 HTML 标记并正如您的标签所指出的那样,可以像这样完成:
查看此 working Fiddle例子!
HTML
<div id="block">
<div id="content">Some content goes here.</div>
<div id="image">
<img src="path_to_image" />
</div>
</div>
CSS
#block {
width: 348px;
display: table; /* set the main wrapper to display as a table */
}
#content {
width: 164px;
padding: 20px;
}
#image {
width: 144px;
display: table-cell; /* set the inner wrapper to display as a cell */
vertical-align: middle; /* tell to vertically align the contents */
}
有必要删除一些与正在使用的技术冲突的 css position
声明。但是你可以在没有它们的情况下实现完全相同的布局,从而允许 CSS vertical-align:middle
按预期工作。
一个 jQuery 解决方案,无需删除任何现有的 CSS 声明即可实现您的标记并实现完全相同的目标:
查看此 working Fiddle例子!
jQuery
获取 #image
内的 img
并收集它的高度,将其除以二,并使用结果值对其应用负边距。
$(function() {
var $target = $('#image').find('img');
$target.css({
"margin-top" : "-" + ($target.height()/2) + "px" // adjust the top margin
});
});
CSS
#block {
width: 348px;
position: relative;
}
#content {
width: 164px;
padding: 20px;
margin-right: 144px;
}
#image {
width: 144px;
position: absolute;
right: 0;
top: 0; /* fit to the top */
bottom: 0; /* fit to the bottom */
/*overflow:hidden;*/ /* optional if the img is bigger that this container */
}
#image img {
position: absolute; /* remove element from the document flow */
top: 50%; /* move it down by 50% of its parent height */
}
HTML
<div id="block">
<div id="image">
<img src="path_to_image" />
</div>
<div id="content">Some content goes here.</div>
</div>
您当前的标记已保留,并添加了一些额外的 CSS 以使其正常工作。让 jQuery 部分尽可能简单!
关于html - 在较小的容器内垂直对齐图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11215260/