【问题标题】:How do I make elements collide with fixed element?如何使元素与固定元素发生碰撞?
【发布时间】:2022-02-01 23:49:26
【问题描述】:

如何让固定元素在重叠时将其他元素推到一边?

我不想要这个:

或者这个:

我想要这个:

我想知道如何使元素发生碰撞或推动,以便我可以轻松对齐元素,而不必逐个像素地定位它们。

编辑:我尝试将div 定位为固定并将其显示为一个块,但其他元素仍与其重叠。甚至可以将元素推离固定元素吗?

【问题讨论】:

  • 固定位置不会与任何其他布局元素发生冲突。这就是它的作用。如果这是您的布局选择,您将需要 JavaScript 将页面中的其他元素移动固定元素的宽度。

标签: html css css-position


【解决方案1】:

甚至可以将元素推离固定元素吗?

我会说不。不是这个概念。

我能想到两种我不推荐的解决方案。

  1. 使用 iframe 实现它。但我不建议这样做。
  2. 使用JS读取宽度并赋值给相邻元素。

在得到一个好的提示后,我更新了我的问题。对于这个例子,我添加了身高 200vh;您可以向下滚动查看它是否有效。

body {
  height: 200vh;
}
.verti {
  background: red;
  width: 200px;
  height: 500px;
  z-index: 10;
  position: fixed;
  top: 8px; 
}

.hori {
  background: green;
  width: 500px;
  height: 200px;
  z-index: 1;  
  position: relative;
  left: 200px;
}
<div class="w">
  <div class="hori"></div>
  <div class="verti"></div>
</div>

【讨论】:

    【解决方案2】:

    尝试使用浮点数?我对这一切都很陌生,但这就是我得到的:

    <body>
        <div id="container">
            <div id="fixed">
                <p class="center-text white">Fixed <br>Element</p>
            </div>
            
            <div id="not-fixed">
                <p class="center-text white">Not Fixed Element</p>
            </div>
        </div>
    
        <style>
            * {
                padding: 0;
                margin: 0;
                font-family:arial;
            }
    
            .center-text {
                text-align:center;
                position:relative;
                top:45%;
            }
    
            .white {
                color:white;
            }
    
            #container {
                margin:10px;
                width:700px;
                height:700px;
            }
    
            #fixed {
                background-color:red;
                position:fixed;
                width:200px;
                height:500px;
            }
    
            #not-fixed {
                position:relative;
                background-color:green;
                width:500px;
                height:200px;
                float:right;
            }
        </style>
    </body>
    

    【讨论】:

    • 感谢您的帮助,但我正在寻找一种方法让固定元素与其他元素发生碰撞。基本上,我正在寻找一种懒惰的方式来将元素放置在固定元素旁边,这样非固定元素就不会出现在固定元素的后面或前面。如果我的问题令人困惑,请不要担心,我将使用传统的定位元素的方式。不管怎么说,还是要谢谢你!您的替代方案也很有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多