In today’s tutorial, I’d like to show you how you can create CSS transparent background. We’ll take a look at two methods, one where we’ll use a solid color and make it transparent, and another one, where we’ll use an image as our background and make that transparent.
Transparent Background with RGBA
The first method we’ll take a look at is with colors. to get use started, let’s create a box, which will have the a semi transparent background.
The HTML
<div id="container"> <!-- Your content here --> </div>
The CSS
body { margin: 0; padding: 0; background: url('background.jpg'); } #container { width: 800px; margin: 0 auto; }
As you can see in the CSS code above, we added a 800px width the box, and centered it. We also added a background image to the body tag, so it’ll be much easier for us to see the semi transparent background.
To add the background, to our #container, we’ll use the background-color property with RGBA colors.
The RGBA color property accepts the following parameters:
rgba(red, green, blue, alpha)
The first 3 parameters, specify how much RED, GREEN and BLUE we want to have in our color.
The 4th one, ( alpha ) specifies the opacity of the color, meaning how transparent it is. This can go from 0 to 1 ( 0, 0.5 etc.. ) We’ll use this to make the background of our box, transparent:
#container { width: 800px; margin: 0 auto; background-color: rgba(0,0,0,0.8); }
As you can see in the code above, we’ve added the background-color property. With rgba(0,0,0,0.8) This will give us a nice black background with the a little transparency.
Transparent Background with Images
To create transparent background with images, we’ll use a css pseudo-element called :after.
#container { width: 800px; margin: 0 auto; padding: 50px; position: relative; } #container:after { content: ''; background: url('header.jpg'); opacity: 0.5; top: 0; left: 0; bottom: 0; right: 0; position: absolute; z-index: -1; }
As you can see, we applied the background to the #container:after and not to the #container itself. This way we can move the image below the container, using position:relative on the #container itself, and position:absolute on the #container:after with a z-index: -1.
Also we added the top:0, left:0,bottom:0, and right:0 to make sure to image is nicely spread inside our container.
And last but not least we have opacity: 0.5 – this specifies how transparent the image in the background is.
As you can see on the image above, using images as transparent background is not quite the greatest idea. You can’t really get out what the image is about, and if you combine two rich image, witha lot of detail, the content will be very hard to make out. If you use a polygonal background image or something, that might work.
What would you use transparent backgrounds for? What you think about them, good, bad? or any other thoughts ?