Computer scienceFrontendCSSBasic propertiesPositioning

Positioning properties

3 minutes read

When working hard on creating a web page, it may be necessary to move a certain block a few pixels to the left, right, lower or higher. To do that, CSS offers intuitive and easy to remember rules for element placement. Let's consider which properties can help position elements and how to work with them.

Property not applicable

Before we begin to work with positioning, it's important to note one small but very important detail. The properties discussed in the next section will not work unless the position property is specified for the required elements. The default value of this property is static.

The value can be anything but static. Thus, we can move an element with position: relative; from its original location to the one we specify with the help of the studied properties.

top

The top property determines how far an item should be moved from the top. It can take both positive and negative values in any unit of measurement, as well as a percentage (the same applies to other properties in the topic).

The black rectangle is under the blue rectangle

Consider the syntax:

div {
  position: relative; 
  top: 10px;
}

In this example, the top edge of the <div> element is shifted down by 10 pixels.

There is an additional position property in the code. Without it, it wouldn't be possible to shift the element.

bottom

The bottom property indicates the distance by which the lower edge of the element is shifted upwards.

The black rectangle is above the blue rectangle

Look at a simple example:

p {
  position: relative; 
  bottom: 5px;
}

This moves up the bottom edge of <p> by 5 pixels.

left

The left property indicates the distance by which the left edge moves to the right. Positive values move the element inside the block where it is located, while negative values move the element outside the block.

The black rectangle is on the right of the blue rectangle

Here is an example:

div {
  position: relative; 
  left: -25px;
}

This moves the left edge of the <div> by -25 pixels.

The right property indicates the distance by which the right edge moves to the left.

The black rectangle is on the left of the blue rectangle

For example:

div {
  position: relative; 
  right: -2%;
}

This code results in the 2 percent offset of the right edge of the <div> block.

Conclusion

With the help of these properties, the arrangement of elements can be set very precisely and flexibly. Positioning is useful in creating complex interfaces, such as galleries or pop-ups, and it surely comes in handy in the layout of small decorative elements. Knowing how to manage the location of the elements, you can create unique pages and web applications that really stand out.

439 learners liked this piece of theory. 11 didn't like it. What about you?
Report a typo