简体   繁体   English

固定位置但相对于容器

[英]Fixed position but relative to container

I am trying to fix a div so it always sticks to the top of the screen, using:我正在尝试修复一个div ,以便它始终粘在屏幕顶部,使用:

position: fixed;
top: 0px;
right: 0px;

However, the div is inside a centered container.但是, div位于居中容器内。 When I use position:fixed it fixes the div relative to the browser window, such as it's up against the right side of the browser.当我使用position:fixed时,它会相对于浏览器窗口固定div ,例如它位于浏览器的右侧。 Instead, it should be fixed relative to the container.相反,它应该相对于容器固定。

I know that position:absolute can be used to fix an element relative to the div , but when you scroll down the page the element vanishes and doesn't stick to the top as with position:fixed .我知道position:absolute可用于固定相对于div的元素,但是当您向下滚动页面时,该元素消失并且不会像position:fixed那样粘在顶部。

Is there a hack or workaround to achieve this?是否有黑客或解决方法来实现这一目标?

Short answer: no.简短的回答:没有。 (It is now possible with CSS transform. See the edit below) (现在可以使用 CSS 变换。请参阅下面的编辑)

Long answer: The problem with using "fixed" positioning is that it takes the element out of flow .长答案:使用“固定”定位的问题在于它会使元素失去流动 thus it can't be re-positioned relative to its parent because it's as if it didn't have one.因此它不能相对于其父级重新定位,因为它就好像它没有一个。 If, however, the container is of a fixed, known width, you can use something like:但是,如果容器具有固定的已知宽度,则可以使用以下内容:

#fixedContainer {
  position: fixed;
  width: 600px;
  height: 200px;
  left: 50%;
  top: 0%;
  margin-left: -300px; /*half the width*/
}

http://jsfiddle.net/HFjU6/1/ http://jsfiddle.net/HFjU6/1/

Edit (03/2015):编辑(03/2015):

This is outdated information.这是过时的信息。 It is now possible to center content of an dynamic size (horizontally and vertically) with the help of the magic of CSS3 transform.现在可以借助 CSS3 变换的魔力将动态大小的内容(水平和垂直)居中。 The same principle applies, but instead of using margin to offset your container, you can use translateX(-50%) .同样的原则也适用,但您可以使用translateX(-50%) ,而不是使用边距来抵消您的容器。 This doesn't work with the above margin trick because you don't know how much to offset it unless the width is fixed and you can't use relative values (like 50% ) because it will be relative to the parent and not the element it's applied to.这不适用于上述边距技巧,因为除非宽度固定并且您不能使用相对值(例如50% ),否则您不知道要偏移多少,因为它将相对于父级而不是它应用到的元素。 transform behaves differently. transform的行为不同。 Its values are relative to the element they are applied to.它的值是相对于它们所应用的元素的。 Thus, 50% for transform means half the width of the element, while 50% for margin is half of the parent's width.因此, transform50%意味着元素宽度的一半,而 margin 的50%是父元素宽度的一半。 This is an IE9+ solution这是一个IE9+ 解决方案

Using similar code to the above example, I recreated the same scenario using completely dynamic width and height:使用与上述示例类似的代码,我使用完全动态的宽度和高度重新创建了相同的场景:

.fixedContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    left: 50%;
    top: 0%;
    transform: translateX(-50%);
}

If you want it to be centered, you can do that too:如果你想让它居中,你也可以这样做:

.fixedContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

Demos:演示:

jsFiddle: Centered horizontally only jsFiddle:仅水平居中
jsFiddle: Centered both horizontally and vertically jsFiddle:水平和垂直居中
Original credit goes to user aaronk6 for pointing it out to me in this answer原始信用归用户aaronk6此答案中向我指出

Actually this is possible and the accepted answer only deals with centralising, which is straightforward enough.实际上这是可能的,并且公认的答案仅涉及集中化,这很简单。 Also you really don't need to use JavaScript.此外,您真的不需要使用 JavaScript。

This will let you deal with any scenario:这将让您处理任何情况:

Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.然后它将相对于容器固定在您想要的任何位置。

For example:例如:

 /* Main site body */.wrapper { width: 940px; margin: 0 auto; position: relative; /* Ensure absolute positioned child elements are relative to this*/ } /* Absolute positioned wrapper for the element you want to fix position */.fixed-wrapper { width: 220px; position: absolute; top: 0; left: -240px; /* Move this out to the left of the site body, leaving a 20px gutter */ } /* The element you want to fix the position of */.fixed { width: 220px; position: fixed; /* Do not set top / left! */ }
 <div class="wrapper"> <div class="fixed-wrapper"> <div class="fixed"> Content in here will be fixed position, but 240px to the left of the site body. </div> </div> </div>

Sadly, I was hoping this thread might solve my issue with Android's WebKit rendering box-shadow blur pixels as margins on fixed position elements, but it seems it's a bug.可悲的是,我希望这个线程可以解决我的问题,即 Android 的WebKit渲染框阴影模糊像素作为固定 position 元素的边距,但它似乎是一个错误。
Anyway, I hope this helps!无论如何,我希望这会有所帮助!

Yes, according to the specs, there is a way.是的,根据规格,有一种方法。

While I agree that Graeme Blackwood's should be the accepted answer, because it practically solves the issue, it should be noted that a fixed element can be positioned relatively to its container.虽然我同意 Graeme Blackwood's 应该是公认的答案,因为它实际上解决了这个问题,但应该注意的是,固定元素可以相对于其容器定位。

I noticed by accident that when applying申请的时候无意中发现

-webkit-transform: translateZ(0);

to the body, it made a fixed child relative to it (instead of the viewport).对于身体,它相对于它(而不是视口)做了一个固定的孩子。 So my fixed elements left and top properties were now relative to the container.所以我的固定元素lefttop属性现在是相对于容器的。

So I did some research, and found that the issue was already been covered by Eric Meyer and even if it felt like a "trick", turns out that this is part of the specifications:所以我做了一些研究,发现这个问题已经被Eric Meyer覆盖了,即使它感觉像是一个“技巧”,结果证明这是规范的一部分:

For elements whose layout is governed by the CSS box model, any value other than none for the transform results in the creation of both a stacking context and a containing block.对于布局由 CSS 框 model 控制的元素,除了 none 之外的任何转换值都会导致创建堆叠上下文和包含块。 The object acts as a containing block for fixed positioned descendants. object 充当固定定位后代的包含块。

http://www.w3.org/TR/css3-transforms/ http://www.w3.org/TR/css3-transforms/

So, if you apply any transformation to a parent element, it will become the containing block.因此,如果您对父元素应用任何转换,它将成为包含块。

But...但...

The problem is that the implementation seems buggy/creative, because the elements also stop behaving as fixed (even if this bit doesn't seem to be part of specification).问题是实现看起来有问题/有创意,因为元素也不再表现得像固定的那样(即使这个位似乎不是规范的一部分)。

The same behavior will be found in Safari, Chrome and Firefox, but not in IE11 (where the fixed element will still remain fixed).在 Safari、Chrome 和 Firefox 中会发现相同的行为,但在 IE11 中不会(其中固定元素仍将保持固定)。

Another interesting (undocumented) thing is that when a fixed element is contained inside a transformed element, while its top and left properties will now be related to the container, respecting the box-sizing property, its scrolling context will extend over the border of the element, as if box-sizing was set to border-box .另一个有趣(未记录)的事情是,当一个固定元素包含在转换后的元素中时,虽然它的topleft属性现在将与容器相关,但考虑到box-sizing属性,它的滚动上下文将延伸到元素,就好像 box-sizing 被设置为border-box一样。 For some creative out there, this could possibly become a plaything:)对于一些有创意的人来说,这可能会变成玩物:)

TEST测试

The answer is yes, as long as you don't set left: 0 or right: 0 after you set the div position to fixed.答案是肯定的,只要在将div position 设置为fixed 后不设置left: 0right: 0即可。

http://jsfiddle.net/T2PL5/85/ http://jsfiddle.net/T2PL5/85/

Checkout the sidebar div.签出侧边栏 div。 It is fixed, but related to the parent, not to the window view point.它是固定的,但与父级有关,与 window 视点无关。

 body { background: #ccc; }.wrapper { margin: 0 auto; height: 1400px; width: 650px; background: green; }.sidebar { background-color: #ddd; float: left; width: 300px; height: 100px; position: fixed; }.main { float: right; background-color: yellow; width: 300px; height: 1400px; }
 <div class="wrapper">wrapper <div class="sidebar">sidebar</div> <div class="main">main</div> </div>

position: sticky that is a new way to position elements that is conceptually similar to position: fixed . position: sticky是 position 元素的新方法,在概念上类似于position: fixed The difference is that an element with position: sticky behaves like position: relative within its parent, until a given offset threshold is met in the viewport.不同之处在于,具有position: sticky的元素的行为类似于position: relative在其父级中,直到在视口中满足给定的偏移阈值。

In Chrome 56 (currently beta as of December 2016, stable in Jan 2017) position: sticky is now back.在 Chrome 56 中(目前为 2016 年 12 月的测试版,2017 年 1 月稳定)position:粘性现在又回来了。

https://developers.google.com/web/updates/2016/12/position-sticky https://developers.google.com/web/updates/2016/12/position-sticky

More details are in Stick your landings: position: sticky lands in WebKit .更多细节在Stick your Lands: position: Sticky Lands in WebKit 中

2019 SOLUTION: You can use position: sticky property. 2019 解决方案:您可以使用position: sticky属性。

Here is an example CODEPEN demonstrating the usage and also how it differs from position: fixed .这是一个示例CODEPEN ,演示了用法以及它与position: fixed的区别。

How it behaves is explained below:它的行为方式解释如下:

  1. An element with sticky position is positioned based on the user's scroll position.基于用户的滚动 position 定位具有粘性 position 的元素。 It basically acts like position: relative until an element is scrolled beyond a specific offset, in which case it turns into position: fixed.它基本上像position: relative ,直到元素滚动超过特定偏移量,在这种情况下,它变成 position:固定。 When it is scrolled back it gets back to its previous (relative) position.当它向后滚动时,它会回到之前的(相对)position。

  2. It effects the flow of other elements in the page ie occupies a specific space on the page(just like position: relative ).它影响页面中其他元素的流动,即占据页面上的特定空间(就像position: relative )。

  3. If it is defined inside some container, it is positioned with respect to that container.如果它是在某个容器内定义的,则它是相对于该容器定位的。 If the container has some overflow(scroll), depending on the scroll offset it turns into position:fixed.如果容器有一些溢出(滚动),根据滚动偏移量,它会变成 position:fixed。

So if you want to achieve the fixed functionality but inside a container, use sticky.因此,如果您想在容器内实现固定功能,请使用粘性。

It is possible to position an element with fixed position relative to its container if the container is using certain containment rules.如果容器使用某些包含规则,则可以 position 相对于其容器具有固定 position 的元素。

<div class='parent'>
  <div class='child'></div>
</div>
.parent {
  contain: content;
}

.child {
  position: fixed;
  top: 0;
  left: 0;
}

Just take the top and left styles out of the fixed position div.只需从固定的 position div 中取出顶部和左侧 styles。 Here's an example这是一个例子

<div id='body' style='height:200%; position: absolute; width: 100%; '>
    <div id='parent' style='display: block; margin: 0px auto; width: 200px;'>
        <div id='content' style='position: fixed;'>content</div>
    </div>
</div> 

The #content div will be sit wherever the parent div sits, but will be fixed there. #content div 将位于父 div 所在的任何位置,但会固定在那里。

I have created this jQuery plugin to solve a similar issue I was having where I had a centered container (tabular data), and I wanted the header to fix to the top of the page when the list was scrolled, yet I wanted it anchored to the tabular data so it would be wherever I put the container (centered, left, right) and also allow it to move left and right with the page when scrolled horizontally.我创建了这个 jQuery 插件来解决我在有一个居中容器(表格数据)时遇到的类似问题,我希望 header 在滚动列表时固定到页面顶部,但我希望它锚定到表格数据,因此它可以放在我放置容器的任何位置(居中、左、右),并且还允许它在水平滚动时随页面左右移动。

Here is the link to this jQuery plugin that may solve this problem:这是这个 jQuery 插件的链接,它可以解决这个问题:

https://github.com/bigspotteddog/ScrollToFixed https://github.com/bigspotteddog/ScrollToFixed

The description of this plugin is as follows:这个插件的描述如下:

This plugin is used to fix elements to the top of the page, if the element would have scrolled out of view, vertically;这个插件用于将元素固定到页面顶部,如果元素会垂直滚动到视图之外; however, it does allow the element to continue to move left or right with the horizontal scroll.但是,它确实允许元素随着水平滚动继续向左或向右移动。

Given an option marginTop, the element will stop moving vertically upward once the vertical scroll has reached the target position;给定一个选项 marginTop,一旦垂直滚动到达目标 position,元素将停止垂直向上移动; but, the element will still move horizontally as the page is scrolled left or right.但是,当页面向左或向右滚动时,元素仍会水平移动。 Once the page has been scrolled back down passed the target position, the element will be restored to its original position on the page.一旦页面向下滚动通过目标 position,该元素将恢复到页面上的原始 position。

This plugin has been tested in Firefox 3/4, Google Chrome 10/11, Safari 5, and Internet Explorer 8/9.此插件已在 Firefox 3/4、Google Chrome 10/11、Safari 5 和 Internet Explorer 8/9 中测试。

Usage for your particular case:针对您的特定情况的用法:

<script src="scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="scripts/jquery-scrolltofixed-min.js" type="text/javascript"></script>

$(document).ready(function() {
    $('#mydiv').scrollToFixed();
});

I had to do this with an advertisement that my client wanted to sit outside of the content area.我必须通过我的客户想要坐在内容区域之外的广告来做到这一点。 I simply did the following and it worked like a charm!我只是做了以下事情,它就像一个魅力!

<div id="content" style="position:relative; width:750px; margin:0 auto;">
  <div id="leftOutsideAd" style="position:absolute; top:0; left:-150px;">
    <a href="#" style="position:fixed;"><img src="###" /></a>
  </div>
</div>

You have a solution if you change position: fixed;如果您更改position: fixed; to position: sticky;position: sticky;

So your code should be:所以你的代码应该是:

position: sticky;
top: 0;
right: 0;

now other divs will not slip underneath.现在其他 div 不会滑到下面。

Two HTML elements and pure CSS (modern browsers)两个 HTML 元素和纯 CSS(现代浏览器)

See this jsFiddle example.请参阅此 jsFiddle 示例。 Resize and see how the fixed elements even move with the floated elements they are in. Use the inner-most scroll bar to see how the scroll would work on a site (fixed elements staying fixed).调整大小并查看固定元素如何与它们所在的浮动元素一起移动。使用最里面的滚动条查看滚动在站点上的工作方式(固定元素保持固定)。

As many here have stated, one key is not setting any positional settings on the fixed element (no top , right , bottom , or left values).正如这里的许多人所说,一个关键是不在fixed元素上设置任何位置设置(没有toprightbottomleft值)。

Rather, we put all the fixed elements (note how the last box has four of them) first in the box they are to be positioned off of, like so:相反,我们将所有固定元素(注意最后一个盒子有四个)放在要定位它们的盒子的首位,如下所示:

<div class="reference">
  <div class="fixed">Test</div>
  Some other content in.
</div>

Then we use margin-top and margin-left to "move" them in relation to their container, something like as this CSS does:然后我们使用margin-topmargin-left来“移动”它们相对于它们的容器,就像这个 CSS 所做的那样:

.fixed {
    position: fixed;
    margin-top: 200px; /* Push/pull it up/down */
    margin-left: 200px; /* Push/pull it right/left */
}

Note that because fixed elements ignore all other layout elements, the final container in our fiddle can have multiple fixed elements, and still have all those elements related to the top left corner.请注意,由于fixed元素忽略了所有其他布局元素,我们小提琴中的最终容器可以有多个fixed元素,并且仍然具有与左上角相关的所有这些元素。 But this is only true if they are all placed first in the container, as this comparison fiddle shows that if dispersed within the container content, positioning becomes unreliable .但这只有在它们都放在容器中的最前面才成立,因为这个比较小提琴表明,如果分散在容器内容中,定位变得不可靠

Whether the wrapper is static , relative , or absolute in positioning, it does not matter.包装器是staticrelative还是absolute定位,都没有关系。

Disclaimer:免责声明:

This answers just the title: Fixed position but relative to container .这只是标题的答案: Fixed position but relative to container For the actual use case the user is asking for position: sticky is the way to go.对于实际用例,用户要求position: sticky是 go 的方式。


https://developer.mozilla.org/en-US/docs/Web/CSS/position https://developer.mozilla.org/en-US/docs/Web/CSS/position

It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none它相对于视口建立的初始包含块定位,除非它的祖先之一的变换、透视或过滤器属性设置为非无

You just need to add a transform to the container and the position of the fixed element will be relative to the container.您只需向容器添加一个变换,固定元素的 position 将相对于容器。 I think a transform: translateX(0);我认为一个transform: translateX(0); should be enough.应该足够了。

You can give a try to my jQuery plugin, FixTo .你可以试试我的 jQuery 插件FixTo

Usage:用法:

$('#mydiv').fixTo('#centeredContainer');

With pure CSS you can't manage to do it;使用纯 CSS 您无法做到; at least I haven't.至少我没有。 However you can do it with jQuery very simply.但是,您可以非常简单地使用 jQuery 做到这一点。 I'll explain my problem, and with a little change you can use it.我会解释我的问题,稍加改动就可以使用它。

So for a start, I wanted my element to have a fixed top (from top of the window), and a left component to inherit from the parent element (because the parent element is centered).因此,首先,我希望我的元素有一个固定的顶部(从窗口顶部),以及一个从父元素继承的左侧组件(因为父元素居中)。 To set the left component, just put your element into the parent and set position:relative for the parent element.要设置左侧组件,只需将您的元素放入父元素并设置position:relative为父元素。

Then you need to know how much from the top your element is when the a scroll bar is on top (y zero scrolled);然后你需要知道当滚动条在顶部时你的元素距离顶部有多少(y 零滚动); there are two options again.再次有两个选择。 First is that is static (some number) or you have to read it from the parent element.首先是 static (某个数字),或者您必须从父元素中读取它。

In my case it's 150 pixels from top static.在我的情况下,它距离顶部 static 150 像素。 So when you see 150 it's how much is the element from the top when we haven't scrolled.所以当你看到 150 时,它是我们没有滚动时从顶部开始的元素的数量。

CSS CSS

#parent-element{position:relative;}
#promo{position:absolute;}

jQuery jQuery

$(document).ready(function() { //This check window scroll bar location on start
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');

});
$(window).scroll(function () { //This is when the window is scrolling
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');
});

I have the same issue, one of our team members gives me a solution.我有同样的问题,我们的一位团队成员给了我一个解决方案。 To allowed the div fix position and relative to other div, our solution is to use a parent container wrap the fix div and scroll div.为了允许 div 修复 position 并相对于其他 div,我们的解决方案是使用父容器包装修复 div 和滚动 div。

 .container { position: relative; flex:1; display:flex; }.fix { position:absolute; }
 <div class="container"> <div class="scroll"></div> <div class="fix"></div> </div>

Yes it is possible as long as you don't set the position ( top or left , etc.) of your fixed element (you can still use margin to set a relative position, though).是的,只要您不设置fixed元素的 position ( topleft等),这是可能的(不过,您仍然可以使用margin来设置相对 position)。 Simon Bos posted about this a while ago .西蒙博斯不久前发布了这个

However don't expect fixed element to scroll with non-fixed relatives.但是不要指望固定元素与非固定亲属一起滚动。

See a demo here .在此处查看演示

Another weird solution to achieve a relative fixed position is converting your container into an iframe, that way your fixed element can be fixed to it's container's viewport and not the entire page.另一个实现相对固定 position 的奇怪解决方案是将您的容器转换为 iframe,这样您的固定元素可以固定到它的容器视口而不是整个页面。

This is easy (as per HTML below)这很容易(根据下面的 HTML)

The trick is to NOT use top or left on the element (div) with "position: fixed;".诀窍是不要在元素(div)上使用“位置:固定;”的顶部或左侧。 If these are not specified, the "fixed content" element will appear RELATIVE to the enclosing element (the div with "position:relative;") INSTEAD OF relative to the browser window!!!如果未指定这些,则“固定内容”元素将显示为相对于封闭元素(带有“位置:相对;”的 div)而不是相对于浏览器窗口!

<div id="divTermsOfUse" style="width:870px; z-index: 20; overflow:auto;">
    <div id="divCloser" style="position:relative; left: 852px;">
        <div style="position:fixed; z-index:22;">
            <a href="javascript:hideDiv('divTermsOfUse');">
                <span style="font-size:18pt; font-weight:bold;">X</span>
            </a>
        </div>
    </div>
    <div>  <!-- container for... -->
         lots of Text To Be Scrolled vertically...
         bhah! blah! blah!
    </div>
</div>

Above allowed me to locate a closing "X" button at the top of a lot of text in a div with vertical scrolling.上面允许我在垂直滚动的 div 中的大量文本顶部找到一个关闭“X”按钮。 The "X" sits in place (does not move with scrolled text and yet it does move left or right with the enclosing div container when the user resizes the width of the browser window, Thus it is "fixed" vertically, but positioned relative to the enclosing element horizontally! “X”就位(不会随着滚动文本移动,但当用户调整浏览器 window 的宽度时,它会随着封闭的 div 容器向左或向右移动,因此它是垂直“固定”的,但相对于水平封闭元素!

Before I got this working the "X" scrolled up and out of sight when I scrolled the text content down.在我开始工作之前,当我向下滚动文本内容时,“X”向上滚动并看不见。

Apologies for not providing my javascript hideDiv() function, but it would needlessly make this post longer.很抱歉没有提供我的 javascript hideDiv() function,但这会不必要地使这篇文章更长。 I opted to keep it as short as possible.我选择让它尽可能短。

/* html */

/* this div exists purely for the purpose of positioning the fixed div it contains */
<div class="fix-my-fixed-div-to-its-parent-not-the-body">

     <div class="im-fixed-within-my-container-div-zone">
          my fixed content
     </div>

</div>



/* css */

/* wraps fixed div to get desired fixed outcome */
.fix-my-fixed-div-to-its-parent-not-the-body 
{
    float: right;
}

.im-fixed-within-my-container-div-zone
{
    position: fixed;
    transform: translate(-100%);
}

It's possible if you use JavaScript.如果您使用 JavaScript,这是可能的。 In this case, the jQuery plugin Sticky-Kit :在这种情况下,jQuery 插件Sticky-Kit

I created a jsfiddle to demostrate how this works using transform.我创建了一个 jsfiddle 来演示如何使用转换。

HTML HTML

<div class="left">
    Content
</div>
<div class="right">
<div class="fixedContainer">
    X
</div>
    Side bar
</div>

CSS CSS

body {
  margin: 0;
}
.left {
  width: 77%;
  background: teal;
  height: 2000px;
}
.right {
  width: 23%;
  background: yellow;
  height: 100vh;
  position: fixed;
  right: 0;
  top: 0;
}
.fixedContainer {
    background-color:#ddd;
    position: fixed;
    padding: 2em;
    //right: 0;
    top: 0%;
    transform: translateX(-100px);
}

jQuery jQuery

$('.fixedContainer').on('click', function() {
    $('.right').animate({'width': '0px'});
  $('.left').animate({'width': '100%'});
});

https://jsfiddle.net/bx6ktwnn/1/ https://jsfiddle.net/bx6ktwnn/1/

My project is .NET ASP Core 2 MVC Angular 4 template with Bootstrap 4. Adding "sticky-top" into main app component html (ie app.component.html) on the first row worked, as follows:我的项目是 .NET ASP Core 2 MVC Angular 4 模板,带有 Bootstrap 4。在主应用程序组件 html 中添加“sticky-top”(即在第一行工作如下 app.component.html)

 <div class='row sticky-top'> <div class='col-sm-12'> <nav-menu-top></nav-menu-top> </div> </div> <div class="row"> <div class='col-sm-3'> <nav-menu></nav-menu> </div> <div class='col-sm-9 body-content'> <router-outlet></router-outlet> </div> </div>

Is that the convention or did I oversimplify this?这是约定还是我过于简化了?

When you use position:fixed CSS rule and try to apply top / left / right / bottom it position the element relative to window.当您使用position:fixed CSS 规则并尝试应用top / left / right / bottom it position 元素相对于 Z245B8C74DE902FFBFBC1.AFFBC1

A workaround is to use margin properties instead of top / left / right / bottom一种解决方法是使用margin属性而不是top / left / right / bottom

The magic is to take the screen width minus the container width and divide it by 2:神奇的是用屏幕宽度减去容器宽度再除以 2:

//1400px is according to container max-width (left can be also right)
.fixed {
  position: fixed;
  right: calc((100vw - 1400px)/2);
}

Note: css calc() function is almost, but not 100% supported.注意: css calc() function 几乎是,但不是 100% 支持。 For most use-cases it is definitely supported enough.对于大多数用例,它肯定得到足够的支持。 Click here for more details点击这里了解更多详情

Snippet (with a 300px container just to fit this website's widget):片段(带有一个 300px 的容器,只是为了适应这个网站的小部件):

 .container { max-width: 300px; margin-left: auto; margin-right: auto; }.fixed { position: fixed; right: calc((100vw - 300px)/2); } @media screen and (max-width: 300px) { right: 0px; }
 <div style="height: 3000px"> <div class="container"> <button class="fixed"> FIXED CONTENT </button> Lorem ipsum dolor sit amet consectetur adipisicing elit. Laborum, eum? Animi quidem accusamus minima vel, dolorem suscipit quia accusantium minus harum modi commodi distinctio, Iste voluptatum earum quam voluptate culpa ad? ipsum dolorum recusandae quis atque eligendi necessitatibus magnam nisi dolores beatae qui, Perspiciatis natus cum nostrum in quod odio sapiente doloremque rerum quo dolore tenetur facere, quisquam atque accusamus fugiat eligendi, deleniti nisi minus recusandae distinctio dignissimos. Dicta quos ipsum qui pariatur at vel veritatis veniam quisquam minus modi et voluptas aliquam laborum, cumque in quo magnam sapiente, Expedita ut dolore laboriosam tempora reprehenderit vero eaque blanditiis, cumque voluptatibus, velit nemo, veniam tenetur quisquam numquam adipisci quae odio repellendus neque incidunt, Cum odio corporis soluta voluptate nesciunt. quasi nobis deleniti neque porro expedita fugiat placeat alias autem pariatur animi error, dicta veritatis atque perspiciatis inventore tempora dolor ad? Mollitia in dolorem ipsam eos porro magni perspiciatis possimus maiores, itaque facere ut, Eos culpa eum error quia incidunt repellendus quam possimus, asperiores earum ipsum molestias dicta sint fugit atque veniam dolorum illo. Officia harum sint incidunt totam. reiciendis illum eos maxime sequi neque repellat quis, expedita eum, corporis quaerat nemo qui soluta aspernatur animi. Sint ad rem numquam omnis sit. </div> </div>

I did something like that awhile back.不久前我做过类似的事情。 I was pretty new to JavaScript, so I'm sure you can do better, but here is a starting point:我对 JavaScript 很陌生,所以我相信你可以做得更好,但这里是一个起点:

function fixxedtext() {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        if (document.body.offsetWidth > 960) {
            var width = document.body.offsetWidth - 960;
            width = width / 2;
            document.getElementById("side").style.marginRight = width + "px";
        }
        if (document.body.offsetWidth < 960) {
            var width = 960 - document.body.offsetWidth;
            document.getElementById("side").style.marginRight = "-" + width + "px";
        }
    }
    else {
        if (window.innerWidth > 960) {
            var width = window.innerWidth - 960;
            width = width / 2;
            document.getElementById("side").style.marginRight = width + "px";
        }
        if (window.innerWidth < 960) {
            var width = 960 - window.innerWidth;
            document.getElementById("side").style.marginRight = "-" + width + "px";
        }
    }
    window.setTimeout("fixxedtext()", 2500)
}

You will need to set your width, and then it gets the window width and changes the margin every few seconds.您需要设置宽度,然后它会获取 window 宽度并每隔几秒更改一次边距。 I know it is heavy, but it works.我知道它很重,但它有效。

I am late to answer this question but I am sure this is a common problem to exist in future as well and will definitely help the future searchers.我迟到了回答这个问题,但我相信这也是未来存在的常见问题,并且肯定会帮助未来的搜索者。

This can be solved by applying a trick.这可以通过应用技巧来解决。 We can use calc here.我们可以在这里使用calc Within calc we can use 100 vertical width and subtract 90% of the width and divide by 2. Please make changes to the 90% as per your needs.在 calc 中,我们可以使用 100 垂直宽度减去 90% 的宽度并除以 2。请根据需要更改 90%。 In your case it can be 100% or 70% whatever depending upon your specific requirement.在您的情况下,根据您的具体要求,它可以是 100% 或 70%。

.your-class {
  position: fixed;
  right: calc((100vw - 90%)/2);
}

This worked for me.这对我有用。 Please note that in my case I intended the floating element to be shifted on the right side.请注意,在我的情况下,我打算将浮动元素移到右侧。 If you want it on the left please use left instead of right.如果你想要它在左边,请使用left而不是 right。

To achieve a similar purpose as the one requested "fixed position relative to container", for me position:fixed was not working since when I scrolled the page the element remained in a fixed position, but you can achieve a similar effect with the overflow feature.为了达到与请求“相对于容器固定 position”类似的目的,对我来说position:fixed不起作用,因为当我滚动页面时元素保持在固定overflow功能.

On the snipet below, check how the heading appears fixed when in the parent container, but when you scroll the body it scrolls too在下面的片段中,检查标题容器中是如何固定显示的,但是当您滚动正文时,它也会滚动

 #grandpa{ width: 100vw; height: 120vh; background-color:rgb(236, 233, 233); overflow:hidden; } #parent{ width: 200px; height: 200px; background-color:teal; overflow:hidden; } #child1{ padding:1em } #child2{ height: 100px; background-color:khaki; overflow-y:scroll; }
 <div id="grandpa"> <div id="parent"> <div id="child1"> heading </div> <div id="child2"> <p>body</p> <p>body</p> <p>body</p> <p>body</p> <p>body</p> <p>body</p> <p>body</p> <p>body</p> </div> </div> </div>

In my experience, the best way to handle this was to kick the element out of the parent element.根据我的经验,处理这个问题的最好方法是将元素踢出父元素。

position: sticky didn't work for me because it didn't stay fixed on scroll, and position:absolute wasn't satisfying because it took it out of the document flow. position: sticky对我不起作用,因为它没有固定在滚动上,并且position:absolute不令人满意,因为它把它从文档流中取出。

What I did simply was put the element at the same level as the parent element (so that they are siblings).我所做的只是将元素放在与父元素相同的级别(以便它们是兄弟姐妹)。 That way it's fixed above the element and isn't taken out of the flow.这样它就固定在元素上方并且不会从流中取出。 No additional complicated css or js required.无需额外复杂的 css 或 js。

In this case, you can change the positions of the fixed element according to its parent element.在这种情况下,您可以根据其父元素更改固定元素的位置。

you can get the position of your parent element using the following code.您可以使用以下代码获取父元素的位置。

function coordinatesSetter() {
    var elm = $('parentElement');
    var rect = elm.getBoundingClientRect(),
    scrollLeft = window.pageXOffset || document.documentElement.scrollLeft,
    scrollTop = window.pageYOffset || document.documentElement.scrollTop;

    return {top: rect.top + scrollTop, left: rect.left + scrollLeft});
 }

Check this:检查这个:

<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title></title>
    </head>
    <body style="width: 1000px !important;margin-left: auto;margin-right: auto">
        <div style="width: 100px; height: 100px; background-color: #ccc; position:fixed;">
        </div>
        <div id="1" style="width: 100%; height: 600px; background-color: #800000">
        </div>
        <div id="2" style="width: 100%; height: 600px; background-color: #100000">
        </div>
        <div id="3" style="width: 100%; height: 600px; background-color: #400000">
        </div>
    </body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM