Home > Software design >  Background color full width of page?
Background color full width of page?

Time:05-27

Hello I am trying to figure out how to have the background-Color say on a paragraph or h1 to just be behind the words not stretch across the page with no writing in it? I’m sorry I am still only learning code I am trying to make a website for my friend and just want it to be right!

Thank you ☺️

CodePudding user response:

You can add CSS styling to a particular type of element, an element with a specific ID, or any elements with a specific class.

For example, you could use the following:

h1 {
    background-color: #f1f2f3;
}
.featured {
    background-color: #fdf7e2;
}
<body>
   <h1>This is a heading</h1>
   <p>This is a paragraph.</p>
   <p >This is a paragraph with a class.</p>
</body>

CodePudding user response:

The reason why the background-color stretches to full width is because <h1>-elements are block-elements. Block-elements will try to take up the full remaining width, relative to its parent - so if the parent is already taking up the full width of the page, so will the <h1>. E.g. see the third example where the <h1>-container has max-width: 50%, where the <h1>-element takes up all that remaining width.

There are several ways to achieve this - in my personal opinion, I think width: fit-content is the best solution here, as this will set the <h1>-elements width equal to the content inside it. This doesn't have full browser support though, but is supported in all major browsers (make sure to use the Firefox prefix)

h1 {
  background-color: limegreen;
}

.fit-content {
  width: fit-content;
  width: -moz-fit-content;
}

.inline-block {
  display: inline-block;
}

div {
  max-width: 50%;
}
<h1>standard h1</h1>
<h1 >fit-content</h1>
<h1 >inline-block</h1>

<div>
  <h1 >with parent</h1>
</div>

  • Related