How to make retreat on the top in CSS

Learn how to create a top margin in CSS with an example. See how to adjust the padding for different elements.

Retreating an element to the top with CSS

The position property in CSS is used to move an element to the desired location on a page. You can set elements to "relative", "absolute" or "fixed" to move them around the page. One of the most common uses for this feature is to retreat an element to the top of the page, as seen in many websites. To do this, you will need to set the position of the element to position:relative; top:0;.

For example, let's say we have a <div> with the following HTML and CSS:

<div class="myDiv">
  This is my div
</div>
.myDiv {
  position: relative;
  top: 30px;
}

This <div> will be positioned 30px from the top of the page. To retreat the <div> to the top of the page, we just need to set the top property to 0. The updated CSS would be:

.myDiv {
  position: relative;
  top: 0;
}

Now the <div> will be positioned at the top of the page. This technique is often used to create sticky headers or footers that remain at the top or bottom of the page while the user scrolls.

Answers (0)