【问题标题】:Position fixed 100 of parent位置固定 100 的父级
【发布时间】:2015-12-13 15:13:37
【问题描述】:

我遇到了困难:我有一个不知道大小的父元素。而且我有一个必须永久放置在主体顶部的项目,然后是position: fixed,但我不能因为给它width: 100%,是主体的100%,但我想要100%的父元素.我该怎么办?

示例:http://codepen.io/michele96/pen/jWbYQb

【问题讨论】:

    标签: css fixed


    【解决方案1】:

    .fixed 的宽度设置为width: inherit; 不要使用100%

    body {
    	padding: 0;
    	margin: 0 auto;
    }
    .container {
    	position: relative;
    	width: 70%;
    	height: 1000px;
    	background: red;
    }
    
    .fixed {
    	position: fixed;
    	width: inherit; /*change here*/
    	line-height: 50px;
    	background: blue;
    	color: #f0f0f0;
    	text-align: center;
    	font-size: 20px;
    }
    <div class="container">
    	<div class="fixed">Navbar Fixed</div>
    </div>

    【讨论】:

    • 在这种情况下是个好主意。但请注意,如果 .container 位于 .super-container 中且 width100% 不同,则它不会起作用。
    【解决方案2】:

    问题在于,与绝对定位元素不同,固定定位元素的包含块通常是视口,而不是它最近的定位元素。然后,width: 100% 根据视口宽度解析。

    有一些方法可以改变这种行为,例如带有transform 的元素为其固定定位的后代建立一个包含块。但是你的元素不会固定在视口的顶部。

    相反,您应该使用粘性定位:

    .fixed {
      position: sticky;
      top: 0;
    }
    

    body {
      padding: 0;
      margin: 0 auto;
    }
    .container {
      width: 70%;
      height: 1000px;
      background: red;
    }
    .fixed {
      position: sticky;
      top: 0;
      line-height: 50px;
      background: blue;
      color: #f0f0f0;
      text-align: center;
      font-size: 20px;
    }
    <div class="container">
      <div class="fixed">Navbar Fixed</div>
    </div>

    请注意,它尚未得到广泛支持。

    【讨论】:

    • @AmrNoman 不好?? .. 说得很好:) .. 但期待我们可以跨浏览器使用它
    【解决方案3】:

    transform: translate3d(0, 0, 0); 设置为父级。

    【讨论】:

    • 只是一个友好的建议,一个完整的代码块将大大提高你的答案的质量。即.container { -webkit-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); }(显然格式正确)以及为什么你说它有效的解释将是加分:)
    猜你喜欢
    • 2017-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-14
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    相关资源
    最近更新 更多