13

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> 
Michael
  • 13,838
  • 18
  • 52
  • 81

2 Answers2

17
  • 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

Teocci
  • 7,189
  • 1
  • 50
  • 48
thirtydot
  • 224,678
  • 48
  • 389
  • 349
  • On second thought, are you sure that you're not just after a Sticky Footer? See: http://ryanfait.com/sticky-footer/ – thirtydot Mar 23 '11 at 00:59
  • **NOTE:** this answer changed the floating div from `position: absolute;` in the original question to `position: fixed;`. Depending on what you are going for, that makes a difference. In my case, only `absolute` scrolled correctly. -- If one doesn't work for you, try the other. See also the set of links about `position` given above. – BCS Mar 21 '23 at 02:15
11

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

Laxman13
  • 5,226
  • 3
  • 23
  • 27