How to Use CSS3’s Right and Left Properties

Published June 12, 2017 by CSS Newbies.

In CSS, the right and left properties can be used to define the space between the right or the left edge of an element and it’s nearest ancestor. If you’re familiar with the margin property, then it might help you to know that in CSS, the right and left properties can be used much the same way in that the margin-right and margin-left properties are used, with a few notable differences.

Unlike with the margin-right and margin-left properties, the right and left properties only work when the element that they’re applied to has a positioning property value of something other than static (this is the default), so the position of the element must be set to either absolute, fixed, or relative in order for the right or the left property to have any effect on the element.

In terms of syntax, the right and left properties are pretty straightforward and easy to use. They accept property values in fixed values, like px or em, or percentages, and the bigger value you use, the more space you’re placing between the right or left edges of your elements and their nearest positioned ancestors. With right and left, you can also use negative values, which is an interesting way to use the properties to play with layouts or element positioning.

To see an example of how you might use the properties in context, take a look at the code snippet below:

div.first{
    right: 10px;
    position: absolute;
}

In the example above, we’re placing 10px of space in between the right side of the div and it’s nearest ancestor. Notice how we also included the position property so that the right property would perform as intended.

div.second{
    left: -30px;
    position: relative;
}

In the second example, we demonstrated how to use the left property and we even gave it a negative value, so that it’s actually removing space between the left side of the div in question and its nearest ancestor. Using negative values like this can cause elements to overlap, so proceed with caution when using this type of value, and don’t overdo it.

Leave a Reply

Your email address will not be published. Required fields are marked *