CSS Properties: How to place an element at a certain distance from top of the document

Go to Exercise page


HTML Code :

 <!DOCTYPE html>
  <title>How to place an element at a certain distance from top of the document</title>
  <style type="text/css">
  div.w3r {
  position: relative;
  width: 300px;
  height: 150px;
  border: 3px solid #3333FF
  div.w3r1 {
  position: absolute;
  top: 50px;
  width: 150px;
  height: 80px;
  border: 3px solid #FF9900
  <h1><strong>w3resource Tutorial</strong></h1>
<div class="w3r">This division element position: relative.
<div class="w3r1">This division element position: absolute. It is placed 50 pixels below the top edge.</div> </div> </body> </html>

Live Demo:

See the Pen top-answer by w3resource (@w3resource) on CodePen.

See the solution in the browser

Supported browser

Firefox logo Chrome logo Opera logo Safari logo Internet Explorer logo

Go to Exercise page

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.

HTML-CSS: Tips of the Day

How does the "position: sticky;" property work?

Sticky positioning is a hybrid of relative and fixed positioning. The element is treated as relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned.

You must specify a threshold with at least one of top, right, bottom, or left for sticky positioning to behave as expected. Otherwise, it will be indistinguishable from relative positioning.

So in your example, you have to define the position where it should stick in the end by using the top property.

HTML Code:

  <ul align="left">
    <li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li>
    <li><a href="#/about" class="nav-selections">About</a></li>
    <li><a href="#/products" class="nav-selections">Products</a></li>
    <li><a href="#" class="nav-selections">Home</a></li>

CSS Code:

html, body {
  height: 200%;

nav {
  position: sticky;
  position: -webkit-sticky;
  top: 0; /* required */

.nav-selections {
  text-transform: uppercase;
  letter-spacing: 5px;
  font: 18px "lato", sans-serif;
  display: inline-block;
  text-decoration: none;
  color: white;
  padding: 18px;
  float: right;
  margin-left: 50px;
  transition: 1.5s;

.nav-selections:hover {
  transition: 1.5s;
  color: black;

ul {
  background-color: #B79b58;
  overflow: auto;

li {
  list-style-type: none;

Live Demo:

See the Pen html css common editor by w3resource (@w3resource) on CodePen.