无法在foreach循环中为各数据集应用不同CSS类的问题排查与修正
Fixing Dynamic CSS Class Assignment for Your Foreach Loop
First, let's break down what's going wrong in your current code:
- You're nesting a
forloop inside yourforeachthat generates four elements per dataset instead of assigning one unique class per dataset. - All your content is wrapped in a single
<li>element, which is invalid for a list—each dataset should be its own list item. - You're repeating the same HTML structure four times, which makes maintenance harder down the line.
Here's the corrected approach that cycles through your bg-img1 to bg-img4 classes for each item in your model, with clean, valid HTML:
Corrected Razor Code
<ul class="imagehover-maindiv"> @foreach (var item in Model.publicShowModelProfileForUI.Select((profile, index) => new { profile, index })) { // Calculate the class number: cycles 1-4 repeatedly for each dataset int classNumber = (item.index % 4) + 1; string bgClass = $"hoverchilddiv bg-img{classNumber}"; <li class="hovermaindiv"> <div class="@bgClass"> <img src="~/Files/ProfilePics/@item.profile.profilepic" width="80" height="80" /> </div> <div class="overlay-text"> <h6 class="overlay-text-clr">@item.profile.profilename</h6> </div> </li> } </ul>
Key Improvements Explained
- Cycling Classes: Using
(item.index %4)+1ensures we loop through 1 to 4 as we iterate over each dataset. So the first item getsbg-img1, secondbg-img2, fourthbg-img4, fifthbg-img1again, and so on. - Valid HTML Structure: Each dataset is now wrapped in its own
<li>element, which follows proper unordered list semantics and will work as expected with your CSS positioning. - DRY Code: We define the HTML structure once instead of repeating it four times, making it easier to update later (e.g., if you change the image size or overlay text styling).
Polished CSS for Consistency
Your existing CSS works, but we can make it more consistent and ensure proper positioning:
/* Base styles for all background image divs */ .bg-img1, .bg-img2, .bg-img3, .bg-img4 { height: 80px; width: 80px; z-index: 99; position: absolute; /* Critical for margin-based positioning to work */ } .bg-img1 { margin-left: -129px; } .bg-img2 { margin-left: -79px; margin-top: 49px; } .bg-img3 { margin-left: -186px; margin-top: 55px; } .bg-img4 { margin-left: -134px; margin-top: 107px; } /* Hover styles shared across all classes */ .bg-img1:hover, .bg-img2:hover, .bg-img3:hover, .bg-img4:hover { transform: scale(1.7); z-index: 99999; /* Ensure scaled item stays on top of others */ }
This should resolve your issue and give you the unique class per dataset you're looking for!
内容的提问来源于stack exchange,提问作者Adarsh
相关产品推荐
相关产品推荐

