CSS left
此CSS属性指定水平定位元素的左偏移量,并且不影响未定位元素。它是
right、top和
bottom的四个偏移属性之一。
同时
left和
right 定义了属性,如果容器是从右到左,则right值具有优先级;如果容器是从左到右,则left值具有优先级。
此属性的效果取决于相应元素的放置方式,即
position 属性的值。设置
position 属性时,
left属性不影响
static 值。
此属性对值
static 以外的定位元素的影响如下:
当元素处于绝对位置或固定位置(即 position:absolute; 和 position:fixed; )时,left属性指定元素左边缘之间的距离及其包含块的左边缘(元素相对定位的祖先)。
如果元素是相对放置的(即 position:relative; ),则left属性会将元素的左边缘从其正常位置设置为左/右。
如果 position 设置为 sticky ,例如 position:sticky; ,则定位上下文是视口。当元素在视口内时,left属性的行为就像其位置是相对的。当元素位于外部时,left属性的行为就像位置固定一样。
语法
left: auto | length | percentage | initial | inherit;
属性值
此属性的值定义如下:
auto:这是默认值。
length:此值以px,cm,pt等形式定义left属性的位置。它允许使用负值。
percentage:此值以百分比(%)定义左侧属性的位置。它被计算为元素包含块的宽度。
initial:它将属性设置为其默认值。
inherit: 它从其父元素继承属性。
示例
在此示例中,有四个绝对位置(即
position: absolute; ) div元素。我们正在向他们应用
left 属性。由于具有相似的尺寸和默认值,具有
left: initial; 和
left: auto; 的div元素将重叠。
在输出中,我们可以看到带有黄色边框的div元素带有
left:auto; ,带有浅蓝色边框的div元素带有
left: initial; 。
<!DOCTYPE html>
<html>
<head>
<title>
CSS left Property
</title>
<style>
div {
position: absolute;
width: 200px;
height: 200px;
font-size: 30px;
}
#len {
left: 250px;
border: 5px solid lightgreen;
}
#per {
left: 65%;
border: 5px solid blue;
}
#auto {
left: auto;
border: 8px solid yellow;
font-size: 40px;
}
#init {
left: initial;
border: 5px solid lightblue;
}
</style>
</head>
<body>
<h1> Example of the left Property </h1>
<div id="len"> left: 250px; </div>
<div id="per"> left: 65%; </div>
<div id="auto"> left: auto; </div>
<div id="init"> left: initial; </div>
</body>
</html>
输出
示例
在此示例中,有四个相对定位(即
position: relative; )的div元素。我们在它们上应用
left 属性。
<!DOCTYPE html>
<html>
<head>
<title>
CSS left Property
</title>
<style>
div {
position: relative;
width: 150px;
height: 100px;
font-size: 30px;
}
#len {
left: 250px;
border: 5px solid lightgreen;
}
#per {
left: 65%;
border: 5px solid blue;
}
#auto {
left: auto;
border: 5px solid red;
}
#init {
left: initial;
border: 5px solid lightblue;
}
</style>
</head>
<body>
<h1> Example of the left Property </h1>
<div id="len"> left: 250px; </div>
<div id="per"> left: 65%; </div>
<div id="auto"> left: auto; </div>
<div id="init"> left: initial; </div>
</body>
</html>
输出
