html - 在精确的中心实现位置粘性内容?

标签 html css

这是一个粘性的跨度,我试图将它准确地放在文档的中心,但我不想给出 margin-left 或 left,因为它没有给出文档的确切中心。

那么有什么办法可以得到位置粘性的精确中心?

.sticky {
  position: sticky;
  top: 0;
  background-color: yellow;
  font-size: 20px;
  left: 50%;
}
p{
  height:500px;
}
<h2>Sticky Element</h2>
<span class="sticky">I am from sticky</span>
<p>Some example text..</p>

最佳答案

使用 display: inline-block ( ? ) 和 transform: translateX(-50%) 使元素水平居中。

.sticky {
  position: sticky;
  top: 0;
  background-color: yellow;
  font-size: 20px;
  left: 50%;
  display: inline-block;
  transform: translateX(-50%);
}
p {
  height:500px;
}
<h2>Sticky Element</h2>
<span class="sticky">I am from sticky</span>

<p>Some example text..</p>

关于html - 在精确的中心实现位置粘性内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59282426/

相关文章:

javascript - 如何添加一个单独的 html 文件

html - 页面内的 Drupal 全屏图像

html - css-grid 以行而不是列呈现 div

HTML 轮播图像裁剪而不是在移动设备上缩放

javascript - 将 boolean 值设置为输入并通过 javascript/jquery 获取字符串类型

css - 定义具有缩放相关大小的 Google map 标记图标

html - 添加 CSS 阴影。阴影只出现在一侧?

html - 溢出 : scroll not working in a specific column grid with Bootstrap 4

html - div中的链接如何垂直居中

javascript - 如何按数组的长度加载多个音频播放器并在每个播放器上播放不同的声音?