Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Darken the background beneath white text in CSS

Tags:

html

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.

like image 802
Sam Avatar asked Mar 27 '15 16:03

Sam


Video Answer


1 Answers

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

div {
  width: 100px;
  height: 100px;
  margin: 20px;
  text-align: center;
  line-height: 100px;
  color: white;
  text-shadow: 0 1px black;
}

.dark {
  background: #333;
}

.light {
  background: #ccc;
}
<div class="dark">Some text</div>
<div class="light">Some text</div>

Or you can ever merge our two approaches.

div {
  width: 100px;
  height: 100px;
  margin: 20px;
  text-align: center;
  line-height: 100px;
}

.dark {
  background: #333;
}

.light {
  background: #ccc;
}

span {
  color: white;
  text-shadow: 0 1px black;
  background: #333;
  background: rgba(0, 0, 0, 0.18);
  padding: 4px 8px;
}
<div class="dark"><span>Some text</span></div>
<div class="light"><span>Some text</span></div>

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 (i.e.: 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 examples above.

like image 111
Bram Vanroy Avatar answered Nov 14 '22 23:11

Bram Vanroy