【问题标题】:How to center an absolutely positioned element within its parent when the child element's height is unknown当子元素的高度未知时,如何将绝对定位的元素在其父元素中居中
【发布时间】:2014-08-15 14:14:43
【问题描述】:

在我的布局中,我试图输出 php 生成的项目。 从数据库中检索到的每个项目都有一个标题、一个图像和一个描述。

我正在尝试生成一个布局,该布局将包含一个缩略图标题,该标题由 img 作为背景(css 样式边框半径:50%)和标题作为中间居中的横幅并占据整个宽度.但是在绝对定位的 div.title 上使用 top 50% 通过顶部边缘居中,并且 div.title 的高度取决于字体大小。

我想知道是否有一种方法可以使标题完美居中,同时考虑到唯一实际已知的尺寸是 div.item 的宽度和所有高度数据,同时保持边框半径效果最终由.thumbnail-wrapper img.title的font-size

决定

html 是

<div id="container">
  <div class="item">
    <div class="thumbnail-wrapper">
      <img />
      <div class="title">Title</div>
    </div>
    <div class="content">Content</div>
  </div>
</div>

CSS

#container {
    width: 600px;
}

.item {
    position: relative;
    display: inline-block;
    width: 50%;
}

.thumbnail-wrapper {
    text-align: center;
    position: relative;
}

.thumbnail-wrapper img {
    border-radius: 50%;
}

.title {
    width: 100%;
    position: absolute;
    top: 50%; /* this is the problem */
}

谢谢!

JSFiddle example

【问题讨论】:

  • 你愿意使用一些 Jquery 和 Javascript 吗?
  • 既然 CSS 可以很好地处理定位,为什么还要加入 JQuery?
  • Moob,它在我的上下文中不起作用,因为这需要将 img 从流中取出,但 img 是为缩略图包装器提供高度的原因。而且由于我事先不知道它的 w/h 比,所以我不能给包装器一个预设的高度。我可以将 img 设置为 background-image 属性,但随后我将失去以我想要的方式应用边框半径的能力。

标签: html css


【解决方案1】:

试试这个 CSS 来使一个绝对定位的元素居中(即添加到div.title):

/* centering css */
   top: 50%;
   left:50%;
   -webkit-transform:translate(-50%,-50%);
   transform:translate(-50%,-50%);

Updated your JSFiddle Demo

Reference

【讨论】:

  • 这是一个很好的解决方案!我可以忍受 IE9- 用户看到一个稍微不居中的标题!非常感谢!
  • “仅适用于 IE9+”严格来说并不正确 - 它也适用于 Firefox、Chrome 等 :) 解决方案和警告都是有效的。
猜你喜欢
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 1970-01-01
  • 2022-08-21
  • 2013-10-21
  • 2014-12-20
相关资源
最近更新 更多