【问题标题】:Absolute positioning regardless of content width绝对定位与内容宽度无关
【发布时间】:2016-02-24 02:31:44
【问题描述】:

总结

如果第一个链接断开,您可以访问示例 hereon the Wayback Machine

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

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

Here's a codepen of this specific element。随便玩#nextVideoTime的内容吧。

问题

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

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

【问题讨论】:

  • 也许你可以用相关代码构建一个小提琴或codepen,它会帮助你得到一些答案:)
  • 刚刚添加了一个codepen。

标签: html css position width


【解决方案1】:

对于#nextVideoTime 删除样式left

并添加

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

【讨论】:

  • 看来当窗口整体宽度发生变化时,时间会独立移动:codepen.io/anon/pen/LpvQaa我打算自己调整一下……
  • 我对其进行了调整,并使用了绝对宽度而不是百分比,它奏效了! codepen.io/anon/pen/ZbZrZr
  • 只需将您的width:27% 替换为width:98px,我会接受您的回答。
【解决方案2】:

我更喜欢这样:

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

【讨论】:

  • 我也喜欢你的方法,只是它比实际需要的复杂性和数据更多。由于图片不会改变大小,我将只使用text-align 方法。还是谢谢你。
  • 除非我必须添加其他将叠加在图像上的元素。两种方法都是有效的 HTML...我认为...
【解决方案3】:

你可以使用宽度和文本对齐:

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

【讨论】:

    猜你喜欢
    • 2014-04-29
    • 1970-01-01
    • 2020-08-21
    • 2023-03-11
    • 1970-01-01
    • 2016-02-06
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多