需要使用position:fixed,但仍然需要流中的元素。怎么办?

问题描述 投票:0回答:3

场景:

在 HTML 中,我有 2 个元素(顶部栏和图像)。顶部栏必须是 在

position:fixed
(这会破坏流程,我理解)。和 第二个元素有
margin-top
可以将图像下推 “顶栏”。在我最小化浏览器宽度之前,这没有问题, “顶栏”中的内容推动容器高度并与第二个重叠 元素,即图像。这看起来很丑。

无论如何,让第二个元素与第一个元素一起流动,这样无论我如何最小化浏览器宽度,第二个元素都是 足够聪明,可以按下去。

代码:CSS

.TopBar {                                   /* 1st Element */
    background-color: #000000;
    opacity: 0.5;
    width: 100%;
    position:fixed;
    padding:10px;   
}
.TopBar > div {
    color:white;
}

.carousel {                                 /* 2nd Element */
    display: inline-block;
    margin-top:73px;
}
.carousel_img {
    width: 100%;
}

问题:

html css css-position
3个回答
2
投票

正如您所知,您无法强迫

position:fixed
流动,因此您的问题没有答案可以按照您想要的方式进行。

但是您描述问题的方式是关于支持不同的浏览器尺寸。如果是这样的话,那么在我看来,媒体查询似乎是您问题的答案。

CSS 支持

@media { ... }
块,它允许您指定仅在某些浏览器尺寸下发挥作用的样式。因此,为了解决您的问题,您需要找出导致布局更改的浏览器宽度(调整大小非常缓慢;它将以特定大小翻转),并编写一个媒体查询来更改小于该大小的样式表.

如果没有(很多)更多布局细节,我无法真正为您提供具体的代码,但是如果您尚未使用它们,可以在线使用很多资源来了解媒体查询。

还值得注意的是,

position:fixed
在浏览器尺寸较小时通常会很麻烦,以至于很多移动浏览器在一段时间内甚至故意不支持它。现在已经改变了,但它仍然可能导致布局问题,因此您可能需要使用媒体查询在低宽度浏览器中完全关闭它。


0
投票

响应Spudley给出的关于使用@media解决问题的答案,我尝试找到一些具有“固定”和溢出元素效果的页面,并通过网络编辑器查看代码来检查代码。这就是我得到的。我慢慢地一一删除所有CSS和相关元素,直到“修复”不起作用。虽然仍然设置为position:relative,但它附加了一个CSS,当我删除它时,“固定”效果就消失了。

参考网址:

https://www.w3schools.com/css/css3_colors.asp

我过滤源文件:

https://drive.google.com/drive/folders/0BzbdjY-H_HzZTC1Rci1nY0F4VFU?usp=sharing

解决我的问题的编码的屏幕截图(我猜)

Click Here to see the screen shot


0
投票

如果我了解您想要实现的目标,则有一种解决方法可以实现类似的结果。

首先,您实际上无法使 TopBar 表现得像具有位置:固定的流动块元素。那么,让我们静态化吧。

“固定”行为将通过设置主体属性来提供

    body {
  /* NOTICE the vertical flex box, makes the height adjust 
     automaticaly (no need to toggle)*/
  display: flex;
  flex-direction: column;
  max-height: 100vh; /* Restrain the body to the window height */
  overflow-y: hidden; /* Prevent scrollbar on body */
}

.TopBar {
  display: block; /* Blocks have 100% widht by default, don't need to 
                     specify */
  padding: 10px;
  position: static; /* No need to specify, it's the default value */
  /* Helpers to make the TopBar easier to track */
  background-color: #000000;
  opacity: 0.5;
  /* This is not part of the solution, it's only to make the height inversely proportional to window width
     e.g. make it grow while the other decrease 
  */
  height: calc(200px - 10vw);
}

/* 
    Just under the TopBar, lets place a container element that will act 
    as scrolling window 
*/

.container {
  height: 100vh; /* max-height is superfluous because of the overflow. */
  /* This will simply make the scrolling on the container instead of the body */
  overflow-y: scroll;
}
.TopBar {
  /* 1st Element */
}
.TopBar > div {
  color: white;
}
/* simply to display some text */
p {
  width: 50%;
  margin: 1em auto;
}

将旋转木马放入容器内,瞧!无需位置或 z 索引摆弄。 TopBar 和容器是流动的,前者会“推”后者。

话虽这么说,一些媒体查询调整不会有什么坏处。根据您的图片,TopBar 中的元素是内联的(内联或内联块)。您应该考虑让它们“阻止”。弹性盒也值得考虑。

希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.