daremkd
daremkd

Reputation: 8424

Position elements both left and right

Is there something about CSS that doesn't allow you to specify both top and bottom or left and right values?

Take this example:

div {
  width: 100px;
  height: 100px;
}
.first {
  background-color: blue;
  position: relative;
  left: 100px;
  right: 50px;
}
.second {
  background-color: yellow;
}
<div class="first"></div>
<div class="second"></div>

Try removing right: 50px and the position will remain the same. What's going on?

Upvotes: 5

Views: 6797

Answers (3)

Asons
Asons

Reputation: 87191

You can combine left/right and top/bottom, but if width/height is also present, their value take precedence, which makes some sense, as how can it be both at a certain right/bottom position and have a certain width/height.

This sample shows how it behaves.

body {
  margin: 0;
}
.first, .second {
  width: 50px;
  height: 50px;
}
.first {
  background-color: yellow;
}
.second {
  background-color: blue;
  position: absolute;
  left: 50px;
  right: 50px;
  top: 50px;
  bottom: 50px;
}
.third {
  background-color: green;
  position: absolute;
  left: 100px;
  right: 100px;
  top: 100px;
  bottom: 50px;
}
<div class="first"></div>
<div class="second"></div>
<div class="third"></div>

Upvotes: 4

web-tiki
web-tiki

Reputation: 103750

In your example, the element has a fixed width to 100px and you are specifying both left and right properties. On MDN, you can read (emphasis mine) :

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)[...]

So in your example the right value is ignored. For the bottom property, the same rule applies as the element's height is fixed.

Note that this rule only applies for non static positioning

Upvotes: 8

Will
Will

Reputation: 20235

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).

Upvotes: 2

Related Questions