CSS Positioning

David
2 min readJun 14, 2021

--

Waterfall flowing over the mouth of a cave
Photo by Joshua Sortino on Unsplash

Introduction

To continue learning CSS, I’ve been looking at CSS positioning. This involves using the CSS position attribute which can be set to either relative or absolute.

relative means that element is positioned normally within the flow of the document relative to any other elements. After defining position as relative, an offset can be applied with the top, bottom, left, right attributes which define the position of the element relative to its normal position.

absolute means that the element is removed from the normal document flow and is positioned relative to the previous positioned ancestor, or if that doesn’t exist, the top left of the page. As with relative, the attributes top, bottom, left, right can be applied.

The Challenge

As a basic challenge, I’ve decided to write a web site “header” image. What I want is an image with a h1 and h2 text positioned on top of the image as shown in the following image.

Picture of a car driving through the desert under the words “Welcome to my world”
Web Site Header Image

The Solution

The HTML for this is fairly straightforward. As before, I’ve created a wrapper container and added the image and text to display. The wrapper class contains a div with a heading class that does most of the work.

<!DOCTYPE html>
<html lang=”en” dir=”ltr”>
<head>
<meta charset=”utf-8">
<title></title>
<link rel=”stylesheet” href=”style.css”>
</head>
<body>
<div class=”wrapper”>
<div class=”heading”>
<img src=”https://picsum.photos/id/551/800/300" alt=”Site Logo”>
<h1>Welcome To My World</h1>
<h2>Developed By Me</h2>
</div>
<p>…</p>
<p>…</p>
</div>
</body>
</html>

The wrapper class simply creates a centred block that is 80% the size of the page:

.wrapper {
width: 80%;
margin: auto;
}

I then define the heading class, setting the position, max-height and overflow properties so that the background image is displayed correctly:

.heading {
position: relative;
max-height: 180px;
overflow: hidden;
}

I want the image to fill the entire width of its container, so I apply that via a CSS rule:

.heading img {
width: 100%;
}

I then define the position of the h1 and h2 elements as absolute, i.e. relative to the div with the heading class.

.heading h1 {
top: 0;
width: 100%;
position: absolute;
text-align: center;
}
.heading h2 {
top: 50px;
width: 100%;
position: absolute;
text-align: center;
}

Finally, I want to bring all subsequent elements, for example the remainder of the page, back into the normal flow of the document. I do this by creating a .heading:after style which is then applied after the heading is displayed.

.heading:after {
content: “”;
clear: both;
display: block;
}

You can see the results on my CodePen

--

--

David
David

Written by David

Full Stack Web Developer, Lover of the Cloud

No responses yet