Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

WordPress

Angelina Bethoney
Angelina Bethoney
117 Points

Changing background colors of different pages

I bet the answer to this is very D'oh! But here it is:

I want my homepage to have a photo as the background. I want all other pages to be a color. Where do I go about putting in the css for the different page? Is there a conditional where it will show that picture only if on the homepage? Or should I put the css in the front-page.php file?

Thanks in advance!

3 Answers

What you'd have to do is to set a css code inline with your HTML, rather than in the external css file.

For your homepage:

<style>
body{ background-image: url('image.png'); }
</style>

and for the other pages:

<style>
body{ background-color: #000000; }
</style>

Alternatively, you can use inline css code. Like this:

<body style="background-color: #000000;"></body>

Another solution is to to put an id attribute on your <body> tag, where the id varies for each page, and then in your css specify your colors for each id. Like this:

<body id="homepage"></body>

<body id="secondpage"></body>

#homepage{ background-image: url('image.png'); }
#secondpage{ background-color: #000000; }
Kevin Korte
Kevin Korte
28,149 Points

Go with adding a class to the body.

Depending on how your WP site is set up, you'll need to know if it's the home.php or the front-page.php file you're targeting. WP gives you two functions, either is_home() or is_front_page()

So then in your template file you have a quick check like

<?php
if ( is_home() ) {
    echo "<body class='home'>";
} else {
 echo "<body>";
} ?>

Than in your CSS you can do your

body.home { background: url('path/to/image.jpg');}
body {background: red;}

This method can be rinsed and repeated for whatever page templates you have, using this WP function

http://codex.wordpress.org/Function_Reference/is_page_template

** Side Note

The only reason I'd set a background image with inline CSS is if I was generating it dynamically. Such as I had an array of image URLs, and I wanted to randomize the background image each time, or you had some other logo that set a background image, you'd be stuck doing inline CSS, and that's okay. Just have a reason to be doing it inline if you're going to do it.