css top 样式

时间:2023-04-05 22:14:53

top 是 CSS 中控制元素上边缘位置的属性,通常与 position 属性搭配使用。top 只能应用在定位元素(即 position 属性值为 absolute 或 fixed)上。

top 的值可以是一个长度值、百分比值或 auto。它表示元素上边缘与其包含块顶部的距离。如果设置为一个负数,元素将向上移动,反之,如果是一个正数,则元素向下移动。

以下是 top 的语法示例:

selector {
top: value;
}

其中 selector 是 CSS 选择器,value 是 top 属性的值。例如,top: 10px 表示将元素的上边缘与其包含块顶部相距 10 像素。

需要注意的是,如果一个元素同时设置了 top 和 bottom 属性,那么它将按照 top 属性的值来确定上边缘位置,而 bottom 属性则会被忽略。

CSS TOP样式 实例,下面是一个使用 top 属性的示例,展示了如何控制元素的上边缘位置。

HTML+CSS top实例代码:

<!DOCTYPE html>
<html>
<head>
<style>
.box {
position: relative;
width: 200px;
height: 100px;
padding: 10px;
border: 1px solid #000;
background-color: #fff;
}

.box1 {
top: 50px;
}

.box2 {
top: 75%;
}

.box3 {
top: -20px;
}
</style>
</head>
<body>
<div class="box box1">
Box 1
</div>
<div class="box box2">
Box 2
</div>
<div class="box box3">
Box 3
</div>
</body>
</html>

在这个例子中,我们使用了三个具有不同 top 值的定位元素,它们分别是 box1、box2 和 box3。box1 的 top 值为 50px,表示将其上边缘与其包含块的顶部相距 50 像素。box2 的 top 值为 75%,表示将其上边缘与其包含块的高度的 75% 相距。box3 的 top 值为 -20px,表示将其上边缘向上移动 20 像素。

相关词 top