Understanding a bit of CSS is a useful skill for a website owner. Now, suppose you wanted to apply a line of CSS styling on just a single page instead of the entire site. Learning how to target your CSS to specific pages can solve hours of frustration when a code snippet isn’t readily available on the internet.
Let’s use this example: we’re going to hide the page title of just the Home Page.
The basic CSS for hiding a page title will usually look like this:
.main-title { display: none; }
When you copy the code above and place it in your styles.css file, it should hide all the page titles in the website. Normally, we’d stop there if that was what we wanted but we just want to hide the page title on the home page.
Basically, the code right now is targeting the display attribute for the main-title element. There is however no indication of which main-title is targeted. Is it the main-title on the home page? Is it the main-title on the About page? For cases like these, all main-titles will be affected.
To target a specific page, you need to add another selector and it looks like this:
.home .main-title { display: none; }
The “.home” part is the part that indicates which main-title we are targeting.
Now, our next challenge will be figuring out what to write in the “.home” part. For that, we need to look at the page source. Look for the start of the <body> HTML. You will then see something like this:
Notice those classes? Those are what we use for the selectors. We can’t just use any of those though because other pages might be using the same classes and if that’s the case, those other pages will be affected by your CSS as well. We have to find the class unique to that page and in this case it is “home”.
On this next example, the unique class which is also the page ID is “page-id-155”. When we make use of “.page-id-155”, we are basically specifying that only that page should be affected by any CSS you write next to it.
However, there are cases where you might have trouble finding the unique class or the page ID is not indicated as one of the classes. In this case, you should go edit that page in the WordPress dashboard. Once you are in the edit page, check out the URL in the address bar. The number corresponding to post= is your page ID that you can then use to target that page.
That’s about it. And do keep in mind that this knowledge isn’t simply limited to your page titles. Here are some more applications:
- Hiding the widget area for some of your pages.
- Reducing/enlarging the main content area depending on the current page.
- Keeping font/color styling on specific pages
When you know the unique class or page ID you can target specific pages with your CSS styling now and I hope it helps you make your website become the best it can be.
Now you know how to specify CSS styling on a single WordPress page. Got questions? Head over to the comments section.
Leave a Reply