htmlcssopacity

How to darken a background using CSS?


I have an element with text in it. Whenever I decrease the opacity, then I decrease the opacity of the WHOLE body. Is there any way I can just make the background-image darker, and not everything else?

background-image:url('http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png');

Solution

  • Just add this code to your image css

     body{
     background:
            /* top, transparent black, faked with gradient */ 
            linear-gradient(
              rgba(0, 0, 0, 0.7), 
              rgba(0, 0, 0, 0.7)
            ),
            /* bottom, image */
            url(https://images.unsplash.com/photo-1614030424754-24d0eebd46b2);
        }

    Reference: linear-gradient() - CSS | MDN

    UPDATE: Not all browsers support RGBa, so you should have a 'fallback color'. This color will be most likely be solid (fully opaque) ex:background:rgb(96, 96, 96). Refer to this blog for RGBa browser support.

    UPDATE 2023: All modern browsers now supports RGBa : caniuse link