2

好的,这是我的问题。我有一个 348px 宽的块,在右侧 144px 上,我想将图像垂直居中。容易,对吧?我的问题是我不知道图像或块的高度。如何将图像垂直居中以越过容器顶部而不使其成为背景图像?

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>

我不知道这会有多大帮助,但希望它会有所帮助。

4

2 回答 2

2

仅使用 CSS 的解决方案,基于您当前的 HTML 标记并由您的标签指出,可以这样完成:

请参阅这个工作小提琴示例!

在此处输入图像描述

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 声明并实现完全相同的目标:

请参阅这个工作小提琴示例!

在此处输入图像描述

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 部分尽可能简单!

于 2012-06-26T22:17:39.093 回答
1

您绝对可以将图像定位在容器内,或者如果这在您的情况下不起作用,则必须使用 javascript 来获取容器的高度和图像的高度并以这种方式定位图像。

通过 CSS 设置:

在您的容器元素上设置“位置:相对”样式。然后,将图像上的样式设置为“position:absolute; top:50%;”。您可能还需要为容器添加高度。

于 2012-06-26T20:21:13.120 回答