Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Position fixed 100 of parent

Tags:

css

fixed

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

like image 617
mikelplhts Avatar asked Dec 13 '15 15:12

mikelplhts


Video Answer


2 Answers

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>
like image 125
Alien Avatar answered Oct 04 '22 00:10

Alien


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.

like image 23
Oriol Avatar answered Oct 03 '22 23:10

Oriol