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.
::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.
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.
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!