相对于父元素的固定位置 [英] Fixed position relative to parent element

查看:98
本文介绍了相对于父元素的固定位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对CSS比较陌生.我遇到了一个问题,试图在其父元素旁边修复一个元素.我可以使用以下代码来做到这一点:

I am relatively new to CSS. I have run into a problem where I am trying to fix an element next to its parent element. I am able to do so with the following code:

父元素:

#search_results{
position:relative;
}  

子元素:

.total {
position: fixed;
top:10px;
width:250px;
left: 75%;
/*overflow: hidden;*/
margin-left: -125px;
}

这很好,直到调整浏览器窗口的大小为止.发生这种情况时,固定元素将与其父元素重叠.您可以在这里看到我的问题: 见证

This works fine until the browser window is resized. When that occurs, the fixed element overlaps its parent element. You can see my problem here: Twittiment

我正在尝试将子元素固定在页面顶部和父元素的右侧.有什么想法吗?

I am trying to fix the child element to the top of the page and the right-hand side of the parent element. Any ideas?

推荐答案

编辑:

您可以使用 position: sticky; 到父元素.

You can use position: sticky; which can be relative to the parent element.

body > div {
  height: 300px;
  background-color: #ddd;
  overflow: auto;
  margin-top: 70px;
}

div > div {
  height: 1000px;
  position: relative;
}

span {
  display: block;
  height: 20px;
  background-color: tomato;
  position: sticky;
  top: 0;
}

<div>
  <div>
    <span>This is a relatively sticky header</span>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus voluptas pariatur ullam, dolores veritatis vero possimus nisi corrupti, provident aspernatur harum ab aliquam expedita assumenda, blanditiis aliquid id consequuntur distinctio.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus voluptas pariatur ullam, dolores veritatis vero possimus nisi corrupti, provident aspernatur harum ab aliquam expedita assumenda, blanditiis aliquid id consequuntur distinctio.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus voluptas pariatur ullam, dolores veritatis vero possimus nisi corrupti, provident aspernatur harum ab aliquam expedita assumenda, blanditiis aliquid id consequuntur distinctio.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Delectus voluptas pariatur ullam, dolores veritatis vero possimus nisi corrupti, provident aspernatur harum ab aliquam expedita assumenda, blanditiis aliquid id consequuntur distinctio.</p>
  </div>
</div>

旧答案:

根据CSS Spec,位于fixed的元素固定在视口而不是包含的元素.

As per CSS Spec, the element positioned fixed is fixed to the viewport and not the containing element.

因此简短的答案是,相对于其父元素,您不能拥有fixed position元素.您可以改用position: absolute;并在运行时使用jQuery/JS调整top left right bottom参数.

So the short answer is NO, you cannot have a fixed position element relative to it's parent element. You can use position: absolute; instead and tweak the top left right bottom parameters on the run using jQuery/JS.

这篇关于相对于父元素的固定位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆