The right
property in CSS is used to position an element relative to its containing element, particularly when the element is positioned using absolute
, fixed
, or relative
positioning. It defines the distance between the element’s right edge and the right edge of its containing element.
Syntax
element { position: value; /* absolute, fixed, or relative */ right: length | percentage | auto; }
Values
length
: Specifies a fixed value in units likepx
,em
,rem
, etc.percentage
: Specifies a percentage of the containing element’s width.auto
: Lets the browser calculate the right position.inherit
: Inherits the right value from the parent element.
Positioning Context
absolute
: The element is positioned relative to its nearest positioned (non-static) ancestor.fixed
: The element is positioned relative to the viewport and does not move when the page is scrolled.relative
: The element is positioned relative to its normal position, butright
will move it leftward if specified.
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> .container { position: relative; width: 300px; height: 200px; border: 1px solid black; } .absolute-box { position: absolute; right: 10px; width: 100px; height: 100px; background-color: lightblue; } .fixed-box { position: fixed; right: 20px; width: 80px; height: 80px; background-color: lightgreen; } </style> </head> <body> <div class="container"> <div class="absolute-box">Absolute</div> </div> <div class="fixed-box">Fixed</div> </body> </html>
Explanation
.container
: A relatively positioned container that serves as the reference for the.absolute-box
..absolute-box
: An absolutely positioned element 10 pixels away from the right edge of its container..fixed-box
: A fixed-position element 20 pixels away from the right edge of the viewport, staying in place even when the page is scrolled.
Notes
- The
right
property has no effect on elements that are statically positioned (default positioning). - When using
right
withrelative
positioning, it moves the element’s position to the left relative to where it would normally appear.
By understanding and using the right
property effectively, you can control horizontal positioning in a variety of layout designs, making your web pages more dynamic and responsive.