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

CSS

How to add a background that simply covers just the content? please help!

Hey, I know by this stage it must look ridiculous that I'm asking this question. I've worked my way through CSS and HTML. So, I'm familiar with the basic concepts....or so it would seem.

I'm currently trying to put theory to practice by messing around. Basically what I am after, is to apply a simple background to a single h1 element. Now, I know that the browser automatically applies the background to the full width of the page, and with CSS you can customise the width. All I'm looking to do is to center the text within a background that just covers the text. Then perhaps add padding and margin. Can someone please show me the code I should use?

Can I just check - you want the background to fit to the space the heading text takes up no matter how big or small and without having to set a specific width for the h1 element?

3 Answers

Try this:

h1 {
display: inline;
background-color: green;
text-align: center;
}

By default h1 elements are a block. By changing them to inline it shrinks the background from being the full width of the containing element.

Hey! yes, that is exactly what I'm looking for. Is there another way to do that without having to find the exact width and height of the element?

Do you mean to get the heading to center on the page? You can accomplish that by putting it in a containing div that has text-align: center applied to it. And the h1 should have the margin and padding that you specified it may or may not have.

Thank you so much! I just applied the code you suggested and it worked!

Awesome, I'm glad it worked for you!