左右定位元素

时间:2015-12-15 13:52:13

标签: css

是否有关于CSS的内容不允许您指定顶部和底部或左右值

选择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>

尝试删除right: 50px,位置将保持不变。发生了什么事?

3 个答案:

答案 0 :(得分:4)

在您的示例中,元素的固定宽度为100px,您指定了leftright属性。在MDN,您可以阅读(强调我的):

  

当正确的CSS属性和左侧CSS属性都是   如果定义,则元素的位置过度指定。在这种情况下,   当容器从左到右时,左值优先   (即正确的计算值设置为-left)[...]

因此,在您的示例中,将忽略正确的值。对于bottom property,同样的规则适用,因为元素的高度是固定的。

请注意,此规则仅适用于非静态定位

答案 1 :(得分:2)

您可以合并left / righttop / bottom,但如果width / height也存在,则其值为优先级,这是有道理的,因为它如何在某个right / bottom位置并且具有某个width / height

此示例显示了它的行为方式。

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

答案 2 :(得分:0)

来自MDN

  

当正确的CSS属性和左侧CSS属性都是   如果定义,则元素的位置过度指定。在这种情况下,   当容器从左到右时,左值具有优先权   (即正确的计算值设置为-left),右侧   当容器从右到左时,值具有优先权(即   左计算值设置为-right)。

相关问题