Position fixed 100 of parent
Asked Answered
R

3

9

I'm in difficulty: I have a parent element that has a size that doesn't know. And I have an item that it must place permanently at the top of the body, then position: fixed, but I cann't because giving it width: 100%, is 100% of the body, but I want 100% of the parent element. How can I do?

Example: http://codepen.io/michele96/pen/jWbYQb

Rheinlander answered 13/12, 2015 at 15:13 Comment(0)
P
14

set .fixed's width as width: inherit; don't use 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>
Pompea answered 13/12, 2015 at 15:19 Comment(1)
Good idea in this case. But note it wouldn't work if .container were inside a .super-container with a width different than 100%.Pricecutting
P
13

The problem is that, unlike absolutely positioned elements, the containing block of a fixedly positioned element is usually the viewport, not its nearest positioned element. Then, width: 100% is resolved with respect to the viewport width.

There are ways to change this behavior, e.g. elements with transform establish a containing block for their fixedly positioned descendants. But then your element won't be fixed at the top of the viewport.

Instead, you should use sticky positioning:

.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>

Note it's not widely supported yet.

Pricecutting answered 13/12, 2015 at 15:18 Comment(1)
@AmrNoman Bad?? .. that was nicely put :) .. but looking forward when we can use it cross browserChafer
P
1

Set transform: translate3d(0, 0, 0); to the parent.

Plan answered 24/7, 2017 at 8:52 Comment(1)
Just a bit of friendly advice, a full code block would severely improve the quality of your answer. i.e. .container { -webkit-transform: translate3d(0, 0, 0); -o-transform: translate3d(0, 0, 0); transform: translate3d(0, 0, 0); } (obviously formatted properly) and an explanation of why you say that it works would be bonus points :)Gasparo

© 2022 - 2024 — McMap. All rights reserved.