Home / Line on Both Sides Heading using CSS Grid
As a front-end website developer many times I am handed a design from the designer and tasked with the job of coding that design into HTML and CSS. It seems like about half of those designs lately has headings with a nice little line on both sides extending the page width. The past few years I have been using the method explained in CSS Tricks that uses a <span> tag inside the <H1> tag. Now that I have been using CSS Grid in a majority of my work, I have come up with a better way as shown below in my Codepen and above.
See the Pen Line on Both Side Heading using CSS Grid! by Jason Houston (@completewebco) on CodePen.
The method uses much less code than the CSS Tricks example, it does not require absolute positioning and will never need to use overflow:hidden. This also does not require the use of an inner tag.
<h1>CSS Grid Rocks!</h1>
h1 { text-align:center; display: grid; grid-template-columns: 1fr auto 1fr; grid-template-rows: 20px 0; grid-gap: 20px; } h1:after,h1:before { content: " "; display: block; border-bottom: 3px solid #4eb982; }
Change the CSS code you can change the style of the line pretty easy.
h1 { text-align:center; display: grid; grid-template-columns: 200px max-content 200px; grid-template-rows: 20px 0; grid-gap: 20px; justify-content:center; } h1:after,h1:before { content: " "; display: block; border-bottom: 3px solid #4eb982; }
By just changing the grid-template columns to 200px we are able to control the actual width of the lines.
h1 { text-align:center; display: grid; grid-template-columns: 1fr max-content 1fr; grid-template-rows: 20px 0; grid-gap: 20px; align-items:center; } h1:after,h1:before { content: " "; display: block; border-top: 1px solid #aaa; border-bottom: 1px solid #aaa; height:3px; } }
Add a border bottom and border top to the :after and :before elements and you get elegant double lines. All using just CSS Grid and your heading tags. No fancy frameworks or inner span tags. No need for absolute positioning.
h1 { text-align:center; display: grid; grid-template-columns: 1fr max-content 1fr; grid-template-rows: 20px 0; grid-gap: 20px; align-items:center; } h1:after,h1:before { content: " "; display: block; height:15px; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='20' height='12' viewBox='0 0 20 12'%3E%3Cg fill-rule='evenodd'%3E%3Cg id='charlie-brown' fill='%236699a1' fill-opacity='0.4'%3E%3Cpath d='M9.8 12L0 2.2V.8l10 10 10-10v1.4L10.2 12h-.4zm-4 0L0 6.2V4.8L7.2 12H5.8zm8.4 0L20 6.2V4.8L12.8 12h1.4zM9.8 0l.2.2.2-.2h-.4zm-4 0L10 4.2 14.2 0h-1.4L10 2.8 7.2 0H5.8z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E"); } }
Add an SVG background to the pseudo elements and you can display any pattern you like. SVG backgrounds can be found at:
Hero Patterns – SVG Backgrounds http://www.heropatterns.com/
Enjoy!
Header Photo Credit: Photo by William Daigneault on Unsplash