Transparent Background with Solid Text

Many times it is required to have background image that look like watermark and above it our text floats. This article will show you how to do that. Its a bit tricky but in the end you will find it simple and worthy to learn.

Demo

This is how our final product will look like. You can change the height and width of the element according to your need.

This is just a sample content. Check out the background.

Concepts

Before we wet our hands writing some real code I want to discuss some concepts. For transparency, CSS has a property opacity. The problem with opacity is that if you give opacity to a parent element then it will automatically be inherited by all the child elements. So we have to use some trick to stop inherting opacity.

For that, we are going to position our parent div as relative. Below that we will put another empty div just containing a background image with opacity. We will assign this div an absolute position so that its position can be changed relative to its parent element. We will stretch this div by setting top, bottom, left, right all to zero. And finally to put it behind the parent div we will assign a z-index which is less than that of parent's z-index.

Rest of the code is easy to understand.

Code

Finally here's all the code that you need. Save both files in the same folder. File names have been written above the code.

index.html

<!DOCTYPE html>
<html>
<head>
	<title>Transparent Background with Solid text</title>
</head>
<body>
<div id="main-box">
    <div id="background-box"></div>
    <div id="content-box">
    This is just a sample content. Check out the background.
    </div>
</div>
</body>
</html>

style.css

#main-box
{
	border:2px solid red;
	width:200px;
	height:200px;
	position:relative;
	z-index:1;
}
#background-box
{
	background:url(bg.png);
	position:absolute;
	top:0;
	bottom:0;
	left:0;
	right:0;
	opacity:0.3;
	filter:alpha(opacity=30);/* For old browsers */
	z-index:-1;
}
#content-box
{
	color:red;
	margin:10px;
	text-align:center;
}