Jump to content

Targeting elements on specific pages with CSS

Occasionally, you'll want to be able to change the style of a particular element on a particular page, without affecting similar elements on other pages. For example, lets say you wanted to change how the .ipsPageHeader element looks in topic view, to make the title bigger, but without changing it for all other pages that also use .ipsPageHeader.


Adding a classname - the wrong way

One method would be to edit the template for topic view, add a classname to the element, and then create a style using that new classname as the selector. This works, but it has a drawback - because you've edited the template, IPS4 won't be able to automatically update it for you when you upgrade to newer versions of the IPS Community Suite. We always suggest you try and avoid editing templates directly, for this reason.


Using page-specific selectors - the right way

There's a better way - every page in IPS4 includes some special attributes on the body tag that identify the app, module and controller being viewed. You can use these to write a CSS selector to only target pages that match the ones you want. Going back to our example, we could target .ipsPageHeader in topic view like so:

body[data-pageapp="forums"][data-pagemodule="forums"][data-pagecontroller="topic"] .ipsPageHeader {
	...your styles

This works because topic view is generated by the topic controller, in the forums module, in the forums app. All pages in the IPS Community Suite follow this controller/module/application structure.

You can mix and match these. If you want to style all page headers in the forums app only, you could simplify the above to:

body[data-pageapp="forums"] .ipsPageHeader {
	...your styles

You can find out the right values to use by going to the page you want to target, viewing the source in a tool like Web Inspector, and finding the body tag - look for the special data-page* attributes that are used for that page.

By including these styles in your custom.css file in your theme, you can target specific elements on specific pages, without making it difficult to upgrade your community later.

  Report Guide

  • Create New...