如何解决容器元素尺寸随标题长度变化的问题?(零基础入门)
Hey there! Nice job diving into coding and following Dev Ed's glassmorphism tutorial—super cool to see you experimenting this early on. Let's get your card layout sorted so elements don't shift around based on the title length.
The Problem
Right now, your .card-info uses justify-content: space-between in a column flex layout. This means when a title is shorter (like "Sackboy" vs. "Assassins Creed Valhalla"), the browser spreads out the elements vertically to fill the space, which throws off the position of your progress bar and the percentage on the right.
The Fix
We'll adjust the flex properties to lock the lower elements (the "PS5 Version" text and progress bar) in place, no matter how long the title is. Here's how to update your code:
Updated CSS
.card { display: flex; background: linear-gradient( to left top, rgba(255, 255, 255, 0.7), rgba(255, 255, 255, 0.5) ); border-radius: 1rem; margin: 2rem 0; padding: 2rem; box-shadow: 6px 6px 20px rgba(122, 122, 122, 0.2); align-items: center; /* Vertically center all card items */ gap: 1.5rem; /* Adds consistent spacing between elements */ } .card img { width: 70px; /* Fix image width to prevent shifting */ height: auto; } .card-info { display: flex; flex-direction: column; flex-grow: 1; /* Let this section fill remaining space */ min-height: 100px; /* Optional: Ensures consistent card height */ } .card-info h2 { margin: 0 0 1rem 0; /* Adds space below the title */ flex-grow: 1; /* Lets title take extra vertical space */ } .card-info p { margin: 0 0 0.8rem 0; } .percentage { width: 60px; text-align: center; margin: 0; }
Cleaned-Up HTML
I removed the unnecessary <span> around the Sackboy title—you don't need that for layout:
<div class="cards"> <div class="card"> <img src="/images/assassins.png" alt="Assassin's Creed Valhalla" /> <div class="card-info"> <h2>Assassins Creed Valhalla</h2> <p>PS5 Version</p> <div class="progress"></div> </div> <h2 class="percentage">60%</h2> </div> <div class="card"> <img src="/images/sackboy.png" alt="Sackboy" /> <div class="card-info"> <h2>Sackboy</h2> <p>PS5 Version</p> <div class="progress"></div> </div> <h2 class="percentage">60%</h2> </div> </div>
What This Does
align-items: centeron.cardkeeps all elements vertically aligned, regardless of content length.flex-grow: 1on.card-infoensures it fills the space between the image and percentage, so those elements stay fixed in place.flex-grow: 1on theh2lets the title take any extra vertical space, locking the text and progress bar at the bottom of the.card-infosection.- Fixed widths on the image and percentage prevent them from shifting when the title changes length.
You're doing great for only two days in—keep experimenting and asking questions!
内容的提问来源于stack exchange,提问作者Marcus Vinicius

