Darken the background beneath white text in CSS

I have a requirement of displaying multiple images in cards and I want to write some text over them. These are random images uploaded by users, so can be of any color. Need the white text on top of them to not be transparent as shown in attached fiddle.

This is an example fiddle - http://jsfiddle.net/7dgpbLd8/1/

This was my solution to add some gray div over image. But, the text should be always white on a gray background. But it is also shadowed here. It would be great to know how to shadow the actual background so text is readable.


Either follow Lee's advice (though I'd recommend adding some padding) or use text-shadow, like so.

div {
    color: white;
    text-shadow: 0 1px black;
}

Or you can ever merge our two approaches.

span {
    color: white;
    text-shadow: 0 1px black;
    background: #333; /* For browsers that don't support RGBA */
    background: rgba(0,0,0,0.18);
    padding: 4px 8px;
}

The problem with your post is that you set the opacity . However, when you lower the opacity, not only does the background change, but also all its content. In other words, the text also has a lower opacity in your fiddle. In my fiddle, presented above, you do not have this problem because you use rgba. RGBA uses the default RGB color representation, but adds an alpha layer component to that (ie: opacity). This means that you can add a color that is (semi-)transparent.

It works in the same way as opacity, simply add the value you want for the color (let's say 0.8), and add it after the default rgb values. An example: RGB for white is 255,255,255 and for black 0,0,0 . If you want those to have an opacity of 0.8, add 0.8 at the back: rgba(255,255,255,0.8) or rgba(0,0,0,0.8) respectively. By doing this, only the opacity of the background will change, and not that of the text. For an example, see the link above.


I would put the image(s) in a div with a dark background, then lower the opacity of the images themselves, darkening the images so you can read the text. This way you can also darken the image on hover for better readability.

http://jsfiddle.net/3w34k1ea/

    .img-wrapper{
    width: 100%;
    height: 100%;
    background: #000;    
}
     img {
      width: 100%
        height: 100%;
        opacity: .5;
}
     img:hover{
    opacity: .3;
}
     p {
    color: white;
    position: absolute;
    top: 15px;
    left: 15px;
    font-size: 20px;
}

I would use text shadow in your position but insteed of one I would experiment with multiples shaodws till reaching the best solution. For example:

text-shadow: 2px 2px 5px rgba(0,0,0,0.8), 0px 0px 2px  rgba(0,0,0,1);

FIDDLE

链接地址: http://www.djcxy.com/p/89352.html

上一篇: 在哪里可以找到css颜色代码

下一篇: 使CSS中白色文本下方的背景变暗