I'm trying to use a text post field for post specific css.
I tried this in my template but it doesn't work
<style>[types field='page-css' output='raw'][/types]</style>
Is there a technique for this?
Thanks,
Ethan
Hi, I don't recommend including CSS directly in a View or Content Template like this. Instead, I recommend using the CSS panel of a View, Content Template, or Layouts CSS & JS, to insert CSS code specific to that View, Content Template, or Layouts in general. You can use CSS selectors to target that content on individual pages if necessary.
For example, let's say you have a View shown on multiple pages. Inside that View, you want to apply a different color text to the span "#my-span", based on the current page. WordPress adds unique classes to each post's body tag, so you can use those classes to help target individual pages. For example, this code targets the span generally, then individually on Page ID 408 and the span on Page ID 109:
#my-span {
color: #000; /* generally black text */
}
.page.page-id-408 #my-span {
color: #999; /* gray text on this page */
}
.page.page-id-109 #my-span {
color: #fc0; /* orange text on this page */
}
Inspect the body tag of any page to determine the proper CSS selectors to apply to that page. I can help with that if you need assistance.
Hi Christian,
Thanks for the reply. Please let me clarify.
I'm taking color as a text field in both term and post fields, and using that on the page. I've got that in at content templat
something like this: background: [types termmeta='tab-active-background-color'][/types] !important;
Should I move this with the code to the css area you mention? This seems to work fine.
thanks,
Ethan
Should I move this with the code to the css area you mention? This seems to work fine.
Right, it may work in some simple implementations but generally I don't recommend including style tags directly in a template for two reasons:
1. It makes it difficult to track down the code when you want to make changes. As your site grows in complexity, this can be a problem.
2. It can lead to more unexpected selector clashes based on the order in which page content is included in the source markup. Again, as your site grows in complexity you may end up with 12 different Views on a page that include different CSS rules for the same class. The last style tag on the page overrides the others. This is a problem because it becomes difficult to know which styles will be applied to your content - you must know which style tag is rendered last on the page.
Instead, I recommend using the CSS panel to insert all the possible variations of the CSS, and apply variable CSS class names to the tags in the View or Content Template. Or, use inline styles applied to each HTML element to set individual rules like
<div style="background-color: #fc0;">
If your site is simple enough and you understand the risks, feel free to do it differently.