Scotts Web Dev Banner
Did you notice... every article on this site has an associated video? Consider subscribing to Scotts Web Dev on YouTube! :)

How To Put Text On Top Of An Image

Why Overlay Text?

Overlaying text can be useful when you want to put text on top of an image. A particular use case for this I can quickly think of is when putting the title of a blog on top of an image. This is exceptionally useful when you use an image overlay combined with this.

The CSS

.container {
   width: 50%;
   height: auto;
   aspect-ratio: 1.5/1;
   margin: 0 auto;
   position: relative;
  }
  .image {
   width: 100%;
   height: 100%;
   object-fit: cover;
   position: absolute;
   top: 0;
   left: 0;
  }
  .container p {
   color: #000;
   text-align: center;
   font-size: 2rem;
   font-weight: bold;
  }
  .container div {
   position: relative;
  }

The Entire Page

Here’s the demo of the entire page so you can play with it and see it in action.

<html>
	<head>
		<title>ScottsWeb.Dev - Text Over Image</title>
	</head>
	<style>
		.container {
			width: 50%;
			height: auto;
			aspect-ratio: 1.5/1;
			margin: 0 auto;
			position: relative;
		}
		.image {
			width: 100%;
			height: 100%;
			object-fit: cover;
			position: absolute;
			top: 0;
			left: 0;
		}
		.container p {
			color: #000;
			text-align: center;
			font-size: 2rem;
			font-weight: bold;
		}
		.container div {
			position: relative;
		}
	</style>
	<body>
		<div class="container">
			<img class="image" src="image.webp" alt="Image" width="500" height="300">
			<div>
				<p>Here's Some Text</p>
			</div>
		</div>
	</body>
</html>

Related Articles