无论内容宽度如何,绝对定位

时间:2015-11-21 17:28:36

标签: html css position width

摘要

如果第一个链接已损坏,您可以访问示例hereon the Wayback Machine

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

Example 1

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

Example 2

Here's a codepen of this specific element。只需使用#nextVideoTime

的内容即可

问题

无论内容的宽度如何,我如何绝对定位元素?

请注意,父元素的宽度是百分比,因此我无法使用right: 280px代替...

3 个答案:

答案 0 :(得分:2)

for #nextVideoTime删除样式left

并添加

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

答案 1 :(得分:1)

我更喜欢这样:

为图像和时间添加了一个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

答案 2 :(得分:-1)

你可以使用width和text-align:

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

相关问题