Darken a background image without affecting the Te

2019-02-15 07:46发布

问题:

I am almost there, but the text inside the a-tag should not be affected by the semi-transparent overlay:

http://jsfiddle.net/ChrisPrefect/GPLfM/

The text should be bright white, regardless if you hover over the image or not.

I can add more html elements if necessary, but I would like to keep it to the minimum.

There is a new element added with:

.tint:before

which has a semi transparent background:

background: rgba(0,0,0, 0.5);

But the "before" element is over the text inside the a-element too and makes it dark.

Can this be solved with z-index ordering?

Thank you! Chris

回答1:

This can easily be solved with ordering your elements z-wise correctly.
Fixed code below, note the use of relative positioning to allow z-indexing and different indexes.
Jsfiddle sample: http://jsfiddle.net/L8hM9/

body {
    color: #fff;
    font-family:arial;
}
a {
    color:#fff;
    position: relative;
}
.block {
    display:block;
    width:250px;
    height:250px;
}


.tint {
    z-index: 2;
    position: relative;
    float: left;
    cursor: pointer;
}  
.tint:before {
    content: "";
    display: block;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0,0,0, 0.5);
    -moz-transition: all .2s linear;
    -webkit-transition: all .2s linear;
    -ms-transition: all .2s linear;
    -o-transition: all .2s linear;
    transition: all .2s linear;
    z-index:3
}  
.tint:hover:before {
    background: none;
}
.tint h2, .tint p {
    position: relative;
    z-index: 4;
}


回答2:

The most straightforward solution is to contain the contents of the link in an element and apply to background to that.

HTML:

<a class="tint t1 block" style="background-image:url(http://cdn.impressivewebs.com/2011-11/greece001.jpg);" href="#">
    <div class="overlay">
        <h2>Themenwoche: Glatt gelogen!</h2>
        <p>Aktueller Beitrag</p>
    </div>
</a>

<a class="tint block" style="background-image:url(http://toxic.fm/site/wp-content/uploads/2014/01/topelement-255x260.jpg)" href="#">
    <div class="overlay">
        <h2>Themenwoche: Glatt gelogen!</h2>
        <p>Aktueller Beitrag</p>
    </div>
</a>

CSS:

body {
    color: #fff;
    font-family:arial;
}

a {
    color:#fff;
}

.block {
    display:block;
    width:250px;
    height:250px;
}

.tint {
    float: left;
    cursor: pointer;
}

.overlay {
    width: 210px;
    height: 210px;
    padding: 20px;
    background: rgba(0,0,0, 0.5);
    -moz-transition: all .2s linear;
    -webkit-transition: all .2s linear;
    -ms-transition: all .2s linear;
    -o-transition: all .2s linear;
    transition: all .2s linear;
}

.overlay *:first-child {
    margin-top: 0;
}

.tint:hover .overlay {
    background: none;
}

See this JSFiddle.