Search code examples
htmlcsscentering

Why does my text go back to left after adding the width so my background stays with text?


So , when I add my width reference to my #information h1 id it completely ignores the text-align: center; reference and puts the text/background to the left instead of center

so basically i need help getting the headers centered with the proper background width so its not backgrounding whitespace

as you can tell im brand new - this is my first time experimenting with html and css - started my course a day or 2 ago

CSS


#information h1{
    text-align: center;
    font-family: Tahoma;
    color: lightcoral;
    background-color: whitesmoke;
    width: 130px;
    margin: 2px;
    border-radius: 25px;
    box-shadow: 2px 2px 2px grey;
    font-size: 25px;
}

HTML

  <section id="information">
    <h1>Information</h1>
    <p>Currently starting my course on becoming a full stack engineer while working on a BS in Computer Science. Open to pretty much anything!<br>
      Looking for part time or full time work while I attend school and courses also open to any development projects!
    </p>
    <h1>Hobbies + More</h1>

WITH WIDTH REFERENCE

headers how i want but not centered

WITHOUT WIDTH REFERENCE Headers without width


Solution

  • Centering text using text-align: center centers the text within the element (in your case that's h1). If you set the elements width to 130px, it centers the text within those 130px (which might even be less wide than the text actually spans, or at least hardly more than that). The element itself still starts at the left side of its container (in your case the body).

    Just don't set the width, as you did before.

    Addition after comment:

    You can use a span element for the text inside the h1, use text-align: center on the h1 and all the other settings on the span inside it:

    #information h1 {
      text-align: center;
    }
    #information h1 span {
      padding: 2px 10px;
      font-family: Tahoma;
      color: lightcoral;
      background-color: whitesmoke;
      border-radius: 25px;
      box-shadow: 2px 2px 2px grey;
      font-size: 25px;
    }
    <section id="information">
      <h1><span>Information</span></h1>
      <p>Currently starting my course on becoming a full stack engineer while working on a BS in Computer Science. Open to pretty much anything!<br> Looking for part time or full time work while I attend school and courses also open to any development projects!
      </p>
      <h1><span>Hobbies + More</span></h1>
    </section>