【问题标题】:How to stick fixed elements to the sides of a centered container?如何将固定元素粘贴到居中容器的侧面?
【发布时间】:2018-05-16 12:31:38
【问题描述】:

我有一个居中的容器,我需要在它的左右两侧粘贴两个元素,这就像背景一样。我可以简单地使用:before:after 元素来做到这一点,这些元素将使用left: -<element_width>;right: -<element_width> 绝对定位。问题是我需要他们的位置是 fixedfixed 定位相对于父级不起作用。

这是fiddle

我怎样才能做到这一点?我不介意在旧浏览器中不起作用的新 CSS 技巧。

【问题讨论】:

  • 也许position: sticky 是一个选项。请参阅hereherehere

标签: html css


【解决方案1】:

您可以使用position: fixedcalc 来实现这一目标

检查下面更新的css

.content {
    width: 50%;
    height: 2000px;
    margin: 0 auto;
    position: relative;
    background: white;
}

.content:before {
    content: "";
    display: block;
    width: 50px;
    height: 200px;
    position: fixed; //fixed position
    left: calc(50% - 25% - 50px); // used calc to determine the correct position
    background: red;
}

说明 left: calc(50% - 25% - 50px);

50% 是将项目定位在页面的中心。

-25% 是父容器值的一半,即50%

-50px:before 向左移动的宽度

快速说明: 大多数浏览器会将fixed 位置元素的默认lefttop 位置设置为其父容器的lefttop,因此,如果您使用position:fixed 而不指定lefttop,则固定元素将默认为其父元素位置

编辑: 如上面 cmets 中提到的 position:sticky 也可以解决问题,但它可能会在旧浏览器和移动设备上产生一些不同的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-12
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多