仅使用 CSS 的解决方案,基于您当前的 HTML 标记并由您的标签指出,可以这样完成:
请参阅这个工作小提琴示例!
![在此处输入图像描述](https://i.stack.imgur.com/dYpuc.jpg)
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 */
}
有必要删除一些position
与正在使用的技术冲突的 css 声明。但是你可以在没有它们的情况下实现完全相同的布局,从而允许 CSSvertical-align:middle
按预期工作。
一个标记的 jQuery 解决方案,无需删除任何现有的 CSS 声明并实现完全相同的目标:
请参阅这个工作小提琴示例!
![在此处输入图像描述](https://i.stack.imgur.com/oJ7LO.jpg)
jQuery
进入img
内部#image
并收集它的高度,将其除以 2 并使用结果值对其应用负边距。
$(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 部分尽可能简单!