I have a foreach loop within my MVC view cycling through my model, and in it a separate div element is rendered for each object in my list. Now, I want the background of this object to be an image with 50% opacity. The image is not the same for iteration of the loop, however, and will depend on one of the parameters of the model object.
To make it clearer, currently I have:
@foreach (var itm in Model)
{
<div id="shell" style="position: relative; etc....">
Many other div elements placed with position: absolute within the shell container.
</div>
}
The name of the image within my content folder can be found by itm.Company + jpeg
, and I want to make this the background image of the div with opacity: 0.5;
I found out here that I can't merely set the background image to the shell div because then I can't change it's opacity without changing the entire div's opacity.
The following answer states I should create it by including another div like:
HTML
<div class="myDiv">
<div class="bg"></div>
Hi there
</div>
CSS
.myDiv {
position: relative;
z-index: 1;
}
.myDiv .bg {
position: absolute;
z-index: -1;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: url(test.jpg) center center;
opacity: .4;
width: 100%;
height: 100%;
}
I tried this:
@foreach (var itm in Model)
{
<div id="shell" style="z-index: 1; position: relative; etc....">
<div class="companyImage" style="z-index:-1; top: 0; bottom: 0; left: 0; right: 0; background: url(~/Content/images/@(itm.Company).jpeg);">
</div>
Many other div elements placed with position: absolute within the shell container.
</div>
}
However, the razor within the url()
part of my companyImage div's style sheet doesn't render properly. I get no error, but the highlighting in VS disappears and it does nothing.
So does anyone know the best way of setting the background image of a div element, with 50% opacity, taking into account that I need to change the image name on each iteration of my foreach loop?