CSS教程
CSS进阶

CSS top

CSS 中的top 属性用于指定垂直定位元素的顶部位置。它不会影响未定位的元素。它是 left、rightbottom的4个偏移属性之一。
此属性的效果取决于相应元素的方式位置,即 position 属性的值。设置 position 属性时, top 属性不起作用
此属性对除值 static 之外的已定位元素的影响如下:
当元素处于绝对位置或固定位置(即 position: absolute; position: fixed ;)时, top 属性指定元素的顶部边缘与其包含块(元素相对放置的祖先)之间的距离。 如果元素相对定位(即 position: relative ;),则top属性会将元素的顶部边缘从其正常位置移到上方/下方。 如果position设置为sticky(即position: sticky;;),则定位上下文是视口。当元素在视口中时, top 属性的行为就像其位置是相对的。当元素位于外部时, top 属性的行为就像其位置是固定的。

语法

top: auto | length | percentage | initial | inherit;

属性值

此属性的值定义如下:
auto:这是默认值。
length:该值定义 top 属性的位置,以px,cm,pt等为单位。
percentage:此值以百分比(%)定义 top 属性的位置。它是根据元素的包含块的高度计算的。
initial:它将属性设置为其默认值。
inherit:它从其父元素继承属性。
现在,让我们通过一些示例来了解此属性。

示例-使用负值

例如,有四个相对定位的div元素。我们将 top 属性应用于带有负值的属性。在这里, top 属性的负长度值在 px em 中定义。
<!DOCTYPE html>
<html>
<head>
<title>
CSS top Property
</title>
<style>
div{
position: relative;
width: 150px;
height: 150px;
font-size: 30px;
}
#len {
top: -75px;
border: 5px solid green;
}
#em {
top: -2em;
border: 5px solid blue;
}
#auto {
top: auto;
border: 5px solid red;
}
#init {
top: initial;
border: 5px solid darkviolet;
}
h1{
text-align: center;
}
</style>
</head>
<body>
<h1> Example of the top Property </h1>
<div id = "len"> top: -75px; </div>
<div id = "em"> top: -2em; </div>
<div id = "auto"> top: auto; </div>
<div id = "init"> top: initial; </div>
</body>
</html>
输出
CSS top属性

示例

在此示例中,有四个绝对定位(即 position:absolute ;)div元素。我们正在向他们应用 top 属性。具有 top:initial; top:auto; 的div元素将重叠,因为它们具有相似的尺寸和默认值。在这里, top 属性的长度以 px 和%定义。
<!DOCTYPE html>
<html>
<head>
<title>
CSS top Property
</title>
<style>
div{
position: absolute;
width: 150px;
height: 150px;
font-size: 30px;
}
#len {
top: 250px;
border: 5px solid lightgreen;
}
#per {
top: 60%;
border: 5px solid blue;
}
#auto {
top: auto;
border: 7px solid red;
}
#init {
top: initial;
border: 5px solid lightblue;
}
</style>
</head>
<body>
<h1> Example of the top Property </h1>
<div id = "len"> top: 250px; </div>
<div id = "per"> top: 60%; </div>
<div id = "auto"> top: auto; </div>
<div id = "init"> top: initial; </div>
</body>
</html>
输出
CSS top属性
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4