在较小的容器内垂直对齐图像

时间:2012-06-26 20:14:22

标签: html css

好的,这是我的问题。我有一个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>

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

2 个答案:

答案 0 :(得分:2)

仅使用CSS 的解决方案,基于您当前的HTML标记以及您的标记所指出的内容,可以像这样完成:

请参阅此working Fiddle示例!

enter image description here

<强> 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示例!

enter image description here

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

答案 1 :(得分:1)

您可以将图像放在容器内,或者如果在您的情况下不起作用,您必须使用javascript来获取容器的高度和图像的高度并定位那样的形象。

通过CSS设置:

设置&#34;位置:亲和&#34;在容器元素上。然后,将图像上的样式设置为&#34; position:absolute;顶部:50%;&#34 ;.您可能还需要为容器添加高度。