Home >Web Front-end >CSS Tutorial >How to Achieve Overlapping Flex Items: Overcoming Shrinking Elements and Implementing Graceful Overlaps?
Overlapping Flex Items
Creating a horizontally overlapping series of elements using flexbox can be challenging, as it can lead to the elements shrinking in size. Let's delve into the issue and explore a solution.
The provided example below demonstrates the problem:
<code class="css">.cards { display: flex; max-width: 300px; } .card { width: 50px; height: 90px; border: 1px solid black; border-radius: 3px; background-color: rgba(255, 0, 0, 0.4); }</code>
<code class="html"><div class='cards'> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> <div class='card'></div> </div></code>
In this example, the cards shrink to fit within the max-width constraint, leading to an undesired result. To resolve this, let's embrace a revised approach:
<code class="css">.cards { display: flex; align-content: center; max-width: 35em; } .cardWrapper { overflow: hidden; } .cardWrapper:last-child, .cardWrapper:hover { overflow: visible; } .card { width: 10em; min-width: 10em; height: 6em; border-radius: 0.5em; border: solid #666 1px; background-color: #ccc; padding: 0.25em; display: flex; flex-direction: column; justify-content: center; align-items: center; }</code>
<code class="html"><div class="cards"> <div class="cardWrapper"> <div class="card">card 1 blah blah blah</div> </div> <div class="cardWrapper"> <div class="card">card 2 blah blah blah</div> </div> <div class="cardWrapper"> <div class="card">card 3 blah blah blah</div> </div> <div class="cardWrapper"> <div class="card">card 4 blah blah blah</div> </div> <div class="cardWrapper"> <div class="card">card 5 blah blah blah</div> </div> </div></code>
In this modified solution, we introduce a wrapper (cardWrapper) around each card. The wrapper acts as a container and controls the overflow behavior of its contents. By default, the wrappers are hidden, but the last wrapper and any wrapper that is hovered upon become visible, allowing the cards to overlap when necessary. This approach ensures that the cards maintain their desired dimensions and overlap gracefully.
The above is the detailed content of How to Achieve Overlapping Flex Items: Overcoming Shrinking Elements and Implementing Graceful Overlaps?. For more information, please follow other related articles on the PHP Chinese website!