我有以下 CSS 代码,它是我正在开发的网站中使用的更大 CSS 代码的一部分:
.cards-u {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
}
.card-u {
margin: 20px;
padding: 20px;
width: 160px;
height: 160px;
line-height: 120px;
justify-content: center;
align-items: center;
text-align: center;
align-self: center;
flex-direction: column;
border-radius: 10px;
box-shadow: 0px 6px 10px rgba(0, 0, 0, 0.25);
transition: all 0.2s;
text-decoration: none;
}
.card-1-u {
background: radial-gradient(#1fe4f5, #3fbafe);
}
在 HTML 代码中我有:
<div class="cards-u"> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 1</h3> </a> <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;"> <h3>Text Sample 2</h3> </a> </div>
但是文本 Text Sample 1 和 Text Sample 2 并未垂直居中,而是位于 Flexbox 的顶部。
看起来我的大型 CSS 代码中的某些内容正在干扰,但我不知道是什么。
我的问题是假设我们不知道 CSS 的其余部分是什么,我们可以强制这部分执行我们想要的操作,即将文本在弹性框中垂直居中吗?
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
发生这种情况是因为 .cards-u 没有定义任何高度。它将内容的高度作为自身的高度并将内容保持在该区域内。
您应该使用 100vh 为 .cards-u 提供完整页面高度,或者执行以下操作:
.cards-u{ position: relative; } .card-u{ position: absolute; top: 50%; transform: translateY(-50%); }