如何在 CSS 中将 align-self 属性设置为默认值?
CSS(层叠样式表)是一个强大的工具,它提供了一系列用于在网页上对齐和定位元素的属性。align-self 属性是 CSS 中众多可用属性之一,用于调整弹性容器内各个弹性项目的对齐方式。默认情况下,align-self 设置为 auto,这意味着元素将继承其父容器的对齐方式。但是,可以通过设置 align-self 属性来更改各个弹性项目的此行为。
scc selector{
align-self: auto;
}
CSS 中的 align-self 属性
在讨论如何将 align-self 属性重置为默认值之前,了解 align-self 的含义非常重要。align-self 属性是 flex 简写属性的子属性;它用于将单个 flex 项目沿容器的横轴对齐。align-self 属性的默认值为 auto,这意味着元素会继承其父容器的 align-items 属性。 align-self 属性可以设置为以下值之一:
Auto(默认)
Flex-start
Flex-end
Center
Baseline
Stretch
如果 align-self 属性设置为 auto 以外的值,它将覆盖该特定元素容器的 align-items 属性。
在 CSS 中将 align-self 重置为默认值
要将 align-self 属性重置为默认值,只需从元素的 CSS 声明中删除该属性的 auto 值即可。例如
.element {
align-self: center;
}
当 align-self 属性从声明中移除后,它将被重置为默认值。
.element {
/* align-self: center; */
}
现在,我们将探讨几个在 CSS 中将 align-self 属性重置为默认值的示例。
使用 Auto 值
将 align-self 属性重置为默认值的简单方法是将其设置为 auto。当 align-self 的值设置为 auto 时,弹性项目将根据弹性容器上设置的 align-items 属性值进行对齐。
示例
在此示例中,我们将使用 auto 值选择所有不包含 .div1 或 .div3 类的 .item 元素,并将其 align-self 属性设置为 auto。这将确保只有 .div1 和 .div3 元素具有自定义 align-self 值。
<!DOCTYPE html>
<html>
<head>
<style>
body { text-align: center; }
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
background-color: lightgray;
}
.item { width: 100px; height: 50px; background-color: white; border: 1px solid black; margin: 10px; }
.div1 { align-self: flex-start; }
.div2 { align-self: auto; }
.div3 { align-self: flex-end; }
</style>
</head>
<body>
<h3>Set align-self property to its default value using the align-self:auto</h3>
<div class="container">
<div class="item div1">HTML</div>
<div class="item div2">CSS</div>
<div class="item div3">JavaScript</div>
</div>
</body>
</html>
使用 :not() 选择器
:not() 选择器是将 align-self 属性重置为默认值的另一种方法。此选择器允许选择所有不符合特定条件的元素。使用 :not() 选择器,我们可以选择除想要应用特定 align-self 值的元素之外的所有元素。
示例
在此示例中,我们将使用 :not() 选择器选择所有不包含 .box1 或 .box3 类的 .item 元素,并将其 align-self 属性设置为 auto。这将确保只有 .box1 和 .box3 元素具有自定义 align-self 值。
<!DOCTYPE html>
<html>
<head>
<style>
h1, h3{ text-align:center;}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
background-color: lightgray;
}
.item:not(.box1):not(.box3) { align-self: auto;}
.item { width: 100px; height: 50px; border: 1px solid black; margin: 10px; background-color:pink; }
.box1 { align-self: flex-start; background-color:lightgreen;}
.box3 { align-self: flex-end; background-color:lightblue; }
</style>
</head>
<body>
<h3>Set align-self property to its default value using the :not() selector</h3>
<div class="container">
<div class="item box1">Java</div>
<div class="item">Python</div>
<div class="item box3">PHP</div>
</div>
</body>
</html>
结论
align-self 属性是设置弹性容器内弹性项目垂直对齐的强大工具。然而,有时我们需要在 CSS 中将 align-self 属性重置为其默认值。通过将 align-self 属性重置为其默认值 auto,或者改用 align-items,我们可以简化 CSS 代码并避免对齐问题。
相关文章
有用资源
css 参考教程 - 该教程包含有关 css 的更多信息:https://www.cainiaomax.com/css/

