【问题标题】:Is there a way to apply multiple CSS position properties to an HTML element? [duplicate]有没有办法将多个 CSS 位置属性应用于 HTML 元素? [复制]
【发布时间】:2020-12-17 22:17:02
【问题描述】:

我需要一个标题 1 元素,它固定在屏幕顶部并具有相对位置。 以下是 HTML 元素:

<h1 class="sticky">Text goes here</h1>

这是 CSS:

.sticky {
    top: 0;
    text-align: center;
    position: relative;
    position: fixed;
    /* I know I cannot add multiple */
    /* position properties, so my */
    /* question really is what should */
    /* I do from here? */
}

出于某种原因,这似乎不起作用。我要么使用粘性,要么使用相对。 有解决办法吗?

【问题讨论】:

  • 一个元素只能有一个位置 - 任何更多都没有意义 - 正如你已经知道的(我假设),第二个 position 只是覆盖第一个。尝试这样做的目的是什么?如果您解释一下您要做什么,我们也许可以提供帮助!
  • 嗯,我基本上需要 h1 元素保持居中,同时保持固定位置。这可能吗?
  • 如何用 span 包裹你的 h1 并给它粘性的类,然后为你的 h1 创建新类并给它应该工作的相对位置
  • @AlwaysHelping 是的,我在评论中承认了这一点。
  • @FluffyKitten 同意你的观点!只要这就是OP所追求的,就不需要span元素。

标签: html css


【解决方案1】:

文本 居中...问题是使用 position:fixed 使 div 的宽度与文本相同,因此它周围没有多余的空间,因此它不会 似乎居中。

您只需将 div 设置为屏幕的整个宽度,然后文本将在整个宽度上居中,而不是在较小的容器中。

.sticky {
    text-align: center;
    position: fixed;
    /* rest of your CSS here... */
}

你可以在这个工作片段中看到它:

.sticky {
    top: 0;
    width:100%;
    text-align: center;
    position: fixed;
}
&lt;h1 class="sticky"&gt;Text goes here&lt;/h1&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-13
    相关资源
    最近更新 更多