Photo by Aditya Chinchure on Unsplash

Creating Border Lines using Pseudo Elements in CSS

holly bourneville
Mar 31 · 3 min read

Have you ever needed to create a border or a line in CSS that isn't the whole width or height of your div? One easy way to tackle creating these lines is through using the ::before & ::after Pseudo Elements.

Borders/Lines created using ::before and ::after

::before and ::after pseudo elements can be used to inject content before and after your stated div. In the cases above — we are using them to create these horizontal and vertical lines.

I will break down the code for these borders below . If you want to skip the explanation and head straight for the code — visit my codepen.

CSS for creating a horizontal line above a div

In the image above, you can see I have a div called .top-and-bottom and I am using ::before to inject some content before this div. The positioning is absolute (the div itself needs to have relative positioning on it so that the content is positioned correctly). After this, the CSS is quite simple. Just think of drawing a line. I want the width to be about 30% of the length of the div, the hight 3px and the I simply position the line where I want it, in this case at the top left of the div.

To create the bottom horizontal line, the CSS is almost the same except I use the ::after pseudo element ( very important tip — you can only have one ::before and one ::after element on a div) and change the positioning to be at the bottom of the div.

CSS to create a vertical Line

The code in the image above shows the minor changes you need to make in order for the line to be vertical rather than horizontal. In this case the width is 3px (how wide across the element is) the height is 90% (just smaller than the div itself).I also needed to change the left position to give the text inside the div enough space.

I know these explanations are almost unnecessary because they are so basic but sometimes it helps to see CSS clearly explained!

The last two corner borders in my first image were each created using both the ::before and ::after pseudo elements combined, e.g one vertical line using ::after and one horizontal line using ::before.

Please let me know your favourite ways to create borders with variable lengths!

Written by

Hi Im Holly! I’m from New Zealand. I’m in my first job as a Front End Web Developer and want to share my learnings and thoughts along the way!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade