与内容宽度无关的绝对定位

Absolute positioning regardless of content width

总结

如果第一个link被破坏,您可以访问示例here, or on the Wayback Machine

我正在尝试对齐包含叠加在图像上的视频时间的元素。我使用 position: absoluteleft: 81px 对齐了它。时间通常由 4 个字符组成(例如 3:33),为元素留出一致的宽度。

但是,当时间超过4个字符时(例如13:33),整个元素向右移动。

Here's a codepen of this specific element。随便玩玩 #nextVideoTime.

的内容

问题

如何在不考虑内容宽度的情况下绝对定位元素?

请注意,父元素有百分比宽度,所以我不能使用 right: 280px 代替...

for #nextVideoTime 删除样式 left

并添加

width:98px;
overflow:hidden;
text-align:right;

您可以使用宽度和文本对齐方式:

body {
  background-color: black;
}

#nextVideo {
  margin-bottom: 50px;
  background-color: #fff;
  height: 75px;
  width: 25%;
  padding: 5px;
  text-align: initial;
  position: relative;
  display: inline-block;
  border-radius: 5px;
}

#nextVideoImage {
  height: inherit;
  float: left;
}

#nextVideoName {
  display: inline-block;
  margin: 0px 0px 0px 5px;
}

#nextVideoName {
  top: 50%;
  position: absolute;
  transform: translateY(-50%);
}
/*----- IMPORTANT PART -----*/

#nextVideoTime {
  position: absolute;
  color: white;
  font-size: 0.7em;
  line-height: 0;
  bottom: 0;
  left:0;
  width:45%;
  text-align:right;
  
}
<div id="nextVideo" onclick="forwardVideo();">
  <span class="fa fa-forward"></span>
  <img id="nextVideoImage" src="//i.ytimg.com/vi/5y_KJAg8bHI/default.jpg">
  <p id="nextVideoName">Avicii - Wake Me Up (Lyric Video)</p>
  <p id="nextVideoTime">33:15</p>
</div>

http://codepen.io/gc-nomade/pen/EVJQrp

我更喜欢这样:

为图像和时间添加了 div。

HTML

<div id="nextVideo" onclick="forwardVideo();">
  <span class="fa fa-forward"></span>
  <div class="container">
    <img id="nextVideoImage" src="//i.ytimg.com/vi/5y_KJAg8bHI/default.jpg">
    <p id="nextVideoTime">13:15</p>
  </div>
  <p id="nextVideoName">Avicii - Wake Me Up (Lyric Video)</p>
</div>

CSS:

.container {
  position: relative;
  float: left;
  height: 100%;
}
#nextVideoTime {
  bottom: 2px;
  margin: 0;
  right: 2px;
}

这里是 DEMO.