Fit background to text


#1

Hello, I’m fairly new to html and css and I have a question!

I was trying to have it so that my paragraphs all had a slightly transparent grey background, which I achieved. However, the background goes all the way across the page, but I want it to fit around the text like a box.

Here is what I have for my paragraph element on my style-sheet:

p {
color: white;
padding-left: 30px;
font-size: 22px;
background: rgba(211,211,211,0.5);
}

I tried changing the padding to the right, changing the margin and border, and changing the background-position, but I couldn’t seem to figure it out.

Thanks in advance for any help!


#2

Paragraph text is not the ideal thing to style. Better that it were in a container, with the background applied to that. Set the width on the container and the paragraph will conform to that width. Also apply the padding to the container, not the paragraph.


#3

I switched my styling to a div element containing the content I want to style. Adjusting the width fixed my problem with the background going all the way across the page, however when I try to add padding, it only affects the text, and not the background. I’m trying to move it just a bit away from the left, but I can’t seem to figure out how. Here is a screenshot of what I’m talking about!:
background
The grey background touches the left edge of my page, which I’m trying to avoid.

Thank you for your help!


#4

Sample

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Centering text and headings</title>
  <style>
    body {
      font-size: 100%;
    }
    div {
      width: 90%;
      margin: 0 auto;
      border: 2px solid black;
    }
    h1 {
      width: 90%;
      margin: 0.5em auto;
      color: white;
      background: gray;
      line-height: 2em;
      font-size: 1.5rem;
      text-align: center;
    }
    p {
      width: 85%;
      margin: 1em auto;
    }
  </style>
</head>
<body>
  <div>
    <h1>Lorem Ipsum Dolor Sit Amet</h1>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</p>
    <p>Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
  </div>
</body>
</html>

text-centering


#5

Thank you! Changing the margin fixed it!