Michael
Michael

Reputation: 14218

Floating div positioning

I need a floating rectangle (100% width, 100px height) to appear exactly 20px above the bottom of a page. How can I do that?

The code below shows the rectangle at the bottom of the browser window not the page - so if the page is taller than what can fit in the screen, the rectangle appears somewhere in the middle of the page.

<div style="z-index: 1; position: absolute; right: 0px; bottom: 20px; background-color: #000000; width: 100%; height: 100px; padding: 0px; color: white; ">&nbsp;</div> 

Upvotes: 13

Views: 84597

Answers (2)

thirtydot
thirtydot

Reputation: 228152

  • As suggested by @Laxman13, you need to add position: relative to the parent of the "floating rectangle". The relevant parent in this case just happens to be the body element.
  • Read this / this / this to help understand the position property.

body {
  position: relative
}

#floatingRectangle {
  z-index: 1;
  position: fixed;
  left: 0;
  right: 0;
  bottom: 20px;
  height: 100px;
  background-color: #000;
  color: white;
  padding: 0;
}
<div id="floatingRectangle">
  <h2>Hello</h2>
</div>
Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />Long content<br />

Live Demo

Upvotes: 17

Laxman13
Laxman13

Reputation: 5211

Add position: relative; to the rectangle div's parent. This will position the div 20px from the bottom of the parent element.

Upvotes: 11

Related Questions