How to use CSS Variables with Examples

February 11, 2020

CSS variables are quickly becoming my favorite thing in web development.  The Custom Properties function in CSS3 is nothing new, but it’s finally becoming more widely accepted and supported.  I also include a few examples on how to implement these in ways that I have found useful.

The best way to be efficient in web development is to avoid redundancy.  Using CSS variables for common values that get repeated throughout a stylesheet is a very helpful way to accomplish this.  I’ve also found them extremely helpful when working with margins, paddings, and the calculations thereafter in layouts and media queries.

How To Use CSS Variables

Let’s look into how to use a CSS variable.  The first step is to set the variable name and value.  We do this by declaring it at the beginning of a style sheet in the :root  psuedo element.  This allows the variable to be accessible by all selectors in the stylesheet.  In this example, we are going to set a variable to a common color we may use throughout the stylesheet.

We have now set the variable “light-blue” to a HEX value that I can use throughout the site, like the following example:

Just like that, the background color for that element will become #336699 and if I ever want to change it, I only need to adjust the variable at the beginning of the stylesheet!  I can use the variable in many selectors for various reasons and only need to refer to one place to ever change that value.

There is also an optional second value when using the variable in the event it isn’t provided:

So, that’s cool and all, but let’s see some examples of how this can be really helpful.

Examples of CSS Variables

Let’s say I have a theme and having consistent spacing is incredibly important.   Well, I can declare a CSS variable for that spacing and re-use it throughout the theme stylesheet:

Let’s take a look at what’s happening here.  I want the spacing of the elements to always be 32 pixels, so I declare my “spacing” variable and then re-use it in a few places.  You can use the variables as one part of the property value, much like I am in both declarations, to make them even more flexible.  The paragraphs will have a property of margin: 32px auto;  and the container will have a property of padding: 32px 0;.

To dive even deeper — there’s a good chance I am going to want to change this value on smaller devices/screens.  Thanks to the flexibility of this function, I can change it through a media query and never have to declare new stylesheet rules!

Now, on devices smaller than 720px, the paragraphs will have a property of margin: 16px auto;  and the container will have a property of padding: 16px 0;.   We’ve updated a property on multiple elements on the site with a single stylesheet rule.  How cool is that??

And if you’re wondering, yes, you can have multiple variables with multiple media queries:

Even more helpful, you can include variables as part of another function like calc()  or another stylesheet value:

The padding for the container will now become 24px (because we divided it in half) and there will be a 2 pixel solid blue border with the color we specified around the element.

IE fallback

Unfortunately, not every browser supports CSS variables.  Most notably, Internet Explorer.  I still come across clients who want this browser compatibility so here is your fallback: Find + Replace!  Haha, just kidding, but seriously — I often develop a site using CSS variables, spare myself valuable time avoiding redundancy, and then find and replace the variable with the value in a text editor or IDE.  It’s stupid and it’s simple.

Conclusion

The possibilities are absolutely endless for CSS variables which is why they have become such a favorable tool for developers.  They’ve become part of my workflow more and more.  On almost every project I find another method of using them which saves me valuable time and typing!

Hope that helps! Happy coding!

CSS Fix For Sticky Headers with the WordPress Admin Bar

December 8, 2019

If you’ve developed themes with HTML & CSS for WordPress, you know that the admin bar often interferes with sticky headers.  The elements overlap each other making one illegible. Both elements are usually placed at the very top and depending what z-index value is used, one is going to appear on top of the other.

Let’s assume you are using a mark-up similar to what is below:

And your CSS for that element could be as simple as:

Well, that unfortunately renders right where WordPress likes to put the admin bar.   It will render something like the image below where the header and admin bar overlap one another.

Luckily, there is a quick CSS fix which will move the sticky element below the admin bar when it is rendered.  If the WordPress admin bar is being used, the <body>  element gets a class of .admin-bar which makes it incredibly easy to make a rule for.  Since the admin bar is 32px in height on desktop and 46px on mobile, we can simply add:

This moves your sticky element below the admin bar, if present, and renders the site how you would expect to see when having two position:fixed; elements.

Spacing for Fixed Elements in the Header

You’ll notice on this site that I use a position:relative; element called .header-spacer  to serve as a “margin” for the fixed header.  I like using this trick to account for the correct spacing you’d like to see with a sticky element so the relative elements aren’t pushed to the top of the page.  Below is an example of the mark up on how I prefer to accomplish this:

And the CSS would be:

The caveat is you need to know your fixed element’s height.  I have found over the years that it is pretty easy to identify and maintain this, even when styling for responsive and mobile. People often use Javascript to calculate the height of the header and then apply that to the header-spacer, but this can often be inconsistent when there are images involved depending on when they are rendered.

I prefer to just code the fixed element, figure out the height, and hard code it in my CSS.  There are many ways to accomplish what I am doing, but I have found that this is the most seamless when manipulating with Javascript actions on scroll.  When the margin/spacing for the main page content is determined in the header, rather than the content, it tends to be more consistent for development going forward.

So in the event I would like this spacing to remain the same with the admin bar present, I would add this to my CSS:

This means going forward, I will have a 100px spacing that is calculated into my page height and content, whether I have the admin bar present or not.  It will adjust accordingly thanks to my CSS.

Again, there are a myriad of ways to accomplish this same task but I prefer this method.  Hopefully it helps you going forward.  Happy coding!

Change the form recipient in Contact Form 7 before sending mail

March 19, 2019

In some cases, I want to simplify the process for clients to change their contact form recipient address.  Rather than have them directly modify the Contact Form 7 settings, I would prefer if they changed the “To” setting when editing the contact page, or the site settings, or something else.  In my case, Advanced Custom Fields always provides a better editing experience to accomplish this.

To the short and sweet, add this to your theme’s functions.php  file:

Let’s talk about what’s happening here.

The wpcf7_before_send_mail is very powerful and allows you modify tons of things before the email sends.  You are creating a custom function here to change what those modifications are.  In this case, we are changing the recipient.

Now, I had mentioned before that I use Advanced Custom Fields to change how someone would update this, so let’s look at how to do that.

Let’s say that I have a contact page and that’s where I would like my client’s to edit the recipient address.  First, I would need to set up a Field Group for that page, and then create a field for them to enter that email address.  Let’s call it “Recipient” and the field name will be “recipient”.

The next part is determining how to grab that field value if we are outside of a loop. In ACF’s case, it’s very simple, but it is completely dependent on your site.  Simply put, you will need the POST ID of your page.  How do you find that?

Easily enough, you can find it in the URL when you are actually editing the page.  It would look just like this:

That “###” is your Post ID.  You can now call your “Recipient” field value outside of the loop:

Let’s put this all together in our function to make it dynamic:

Now, whenever someone edits the “Recipient” field in the Post you selected, the email address will get updated before the email sends out.  If it is left blank, CF7 will use the traditional “To” field to determine the recipient.

There is a ton more customization you can accomplish with this hook.  Don’t be afraid to explore more and have more control over the editing process you provide for your clients.  Thanks, and happy coding!

Toggle A Caption in Fancybox 3

March 27, 2018

View Demo on CodePen View Project on GitHub

Since the release of Fancybox 3 and all of its new options, I started looking for a way to incorporate the caption of an image and toggle it.  The default effect of this JQuery lightbox plugin is to hide and show the caption (along with all of the UI) when the lightbox is hovered.  I have adjusted this slightly so there is a toggle button added to the options and it toggles the caption.

There are two sections to creating this effect, the Javascript and the CSS.

Adjusting the CSS

While I don’t recommend adjusting the CSS file you call when implementing Fancybox 3, you can easily add your own CSS lines to override the default styling.

I am adding a little padding, adjusting the transition property to accommodate the toggle-in, and placing it out of the viewport so the user can’t see it.  I am also declaring a property for the class I will add to the Fancybox caption when toggled.  This allows us to control the styling and transition when it is in toggled on and off.

I am also adjusting the width of the custom button I plan on creating so it is not fixed like the others.

Adding Javascript to modify Fancybox 3 and its settings

Thanks to the Fancybox 3 documentation, it is incredibly easy to modify how the plugin animates and controls your content.  Normally, Fancybox 3 will work out of the box by simply adding a data-fancybox  attribute to your HTML element, but in this case we need to go a little further to adjust the settings.

In this case, we will be doing two things –

  1. Declaring a custom button for Fancybox 3
  2. Adding a click event to the button which toggles a CSS class

So, how do we do that?

Well, first, we are going to create the button with this Javascript:

Now, we need to ensure that when Fancybox is called that it understands to use our new button.  Let’s call Fancybox and determine which buttons it should use:

Lastly, we need to add a click event on this button, so it knows what to do!

Here we are saying — if this button is ever clicked, see if the caption already has our toggled class, and if not — add it!

That’s it!  You now have a Fancybox 3 plugin that toggles the caption.

Hopefully with this example, you are able to see the flexibility and customization the developers at FancyApps provide to their already stellar plugin.  You could easily develop a custom user-experience that goes much further than a simple Lightbox effect.  Feel free to comment and send me examples!

 

Embed A Tumblr Feed In WordPress

January 19, 2017

Below is an example showing how to embed multiple Tumblr posts as a feed into a WordPress site.  You will need a little coding experience with PHP and access to your WordPress theme files.  It is also required to have a Tumblr API key.

1. Get A Tumblr API key

This is required to use Tumblr’s API for requests.  In this case, we will be using it to fetch the latest posts from a Tumblr user.  You can visit here to set up an APP and retrieve your API key.

2. Set Up Your Shortcode

A shortcode is a simple WordPress snippet that you can pop into the page/post editor to place some code, make a query, or anything else you could possibly want.  Today, we are going to fetch Tumblr posts with PHP and place them in the site.

Editing the functions.php file of your WordPress theme, place this code at the bottom before the PHP end tag:

Let’s talk a little about what is happening here.

There are 3 variables you need to define at the beginning of the code:

  1. Your API key
  2. The amount of posts you want
  3. The Tumblr URL of the posts you want

The code will then fetch those posts and return them in JSON format.  In your foreach loop, you could cycle through each one of those objects in the array and pull any information you would need from each post.  In this case, I only want the post URL.

I only want the post URL because I am going to use a very handy function from WordPress to do the hard work for me.  Instead of figuring out whether each post is a link, a video, a photo, an embed, and then trying to format the HTML for each one, I will use what WordPress already provides, the oEmbed function.  That functionality takes whatever URL you paste in your WordPress text editor and then tries to find the embed code for it and place it within your content.

WordPress also provides a function to initiate this feature however you please: wp_embed_get();

So for this line of code:

we are just looping through each returned Tumblr post via JSON, and running it through the WordPress embed function wp_embed_get().

3. Place your shortcode where you want the feed

By adding the line below, you will call the function we placed in our functions.php file, and it will place it where the shortcode was used.

This shortcode can be placed anywhere on a page, post, or custom post type in the content editor.

You can customize a lot of the functionality to suit your needs, but hopefully this gets you started working with the Tumblr API and the many ways you can dynamically call Tumblr content on your WordPress site.

Credit

I want to credit @groovycarrot for his post describing how to first work with the Tumblr API in PHP which inspired the idea.