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

标签 html css

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

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

获取 #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/

相关文章:

HTML - 图像框阴影不覆盖图像边框

javascript - 在同一个 View 中使用 ionic 的多个 Controller

css - 如何将 Material-UI 托管样式应用于非 Material-UI、非 React 元素?

html - 如何垂直对齐标签和选择?

javascript - 如何调整 SVG 的大小?

javascript - 为什么这个线性颜色渐变不移动?尝试对渐变中颜色停止的位置进行动画处理

javascript - 如何在不将用户重定向到该 URL 页面的情况下发送 GET 值?

html - 如何将 `overflow` 保存在 flex 容器中?

javascript - 生成具有随机背景色的表格单元格,然后显示背景色的十六进制值

javascript - 显示隐藏不适用于选项卡