Using Base URLs in Codepen Pens

productivity / webdev

Using Codepen more and more, often to experiment and for demos to show the code I’m working with, I’ve learned to make my Codepen workflow smoother with little tacks here and there. One of which is finding a way to avoid repeating a same base URL in the HTML, in Pens. Here’s what I mean…

It could be a set of hyperlinked texts to different articles from a same website, or images displayed from a same CDN — In such cases using absolute URLs and repeating the same domain in each URL can crowd the HTML (well, kinda). So, if the requested resources can be called instead with relative URLs then that would clean up the code and readers can focus on the main code.

For instance, instead of something like this:

We can have this, cleaner version:

Making this change is really simple. We use the HTML base element.

What’s the base tag for?

This element, to be placed inside head, assigns a base URL for the document. By doing this, unless a URL is absolute in the HTML document it’ll be treated as a relative URL, relative to the document’s base URL.

Codepen has a setting for adding codes inside the head element of the result document (codes like meta tags and links). We use that setting to add the base tag.

Open the pen and click Settings, if not already selected, select the HTML tab. Under Stuff for head type the base element with its href attribute containing the base URL.

Now your Pen’s HTML has a base URL that you can use to fetch any resource in it.


The Author

Web developer and writer. @rpsthecoder in Twitter.