northerner northerner - 9 months ago 29
CSS Question

How do these values take precedence in CSS?

I'm learning CSS and am confused by relative layout. What happens if you give conflicting property values for positioning? For example

left: 50px;
and
right 50px;


I've tried myself and from what I can tell,
right
always gets dropped if there is both
left
and
right
. Also what about
top
vs
bottom
?

Example

<!DOCTYPE html>
<html>
<head>
<style>
div.relative {
position: relative;
left: 30px;
right: 30px;
border: 10px solid #73AD21;
}
</style>
</head>
<body>

<h2>position: relative;</h2>

<p>Lorem Ipsum insert text here....</p>

<div class="relative">
This div element has position: relative;
</div>

</body>
</html>

Answer Source

From MDN:

When both the right CSS property and the left CSS property are defined, the position of the element is overspecified. In that case, the left value has precedence when the container is left-to-right (that is that the right computed value is set to -left), and the right value has precedence when the container is right-to-left (that is that the left computed value is set to -right).

So, when direction: ltr, left has precedence. When direction: rtl, right has precedence.

For top and bottom (MDN):

When both top and bottom are specified, as long as height is unspecified, auto or 100%, both top and bottom distances will be respected. Otherwise, if height is constrained in any way, the top property takes precedence and the bottom property is ignored.