0

body {
    background-color: darkslateblue;
}
.colorbackground{
    text-align: center;
    background-color: red;
    font-size: 20px;
    color: white;
}
<!DOCTYPE HTML>
<html>
    
<head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Background Color Test</title>
    
    <link rel="stylesheet" href="style.css">
    
</head>
       
<body>
    
    <div class=colorbackground>
    
        <h1>Hello World!</h1>
        
    </div>       
    
</body>

</html>

What are some ways that I can modify this sample of code so that the red background only covers the "Hello World!" text only by a few spaces on either side of the text?

dwwentz88
  • 9
  • 1

3 Answers3

1

You can do it like so:

body {
  background-color: darkslateblue;
}
.wrapper{
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.colorbackground {
  flex-grow: 0;
  text-align: center;
  font-size: 20px;
  background-color: red;
  color: white;
  padding: 0 20px;
}
<body>
  <div class="wrapper">
    <div class="colorbackground">
      <h1>Hello World!</h1>
    </div>
  </div>
</body>

Learn more about flexbox

YourBrainEatsYou
  • 979
  • 6
  • 16
1

You can make the h1 inline-block, set the background colour to the h1 instead of the div and add padding to the h1

body {
    background-color: darkslateblue;
}
.colorbackground{
    text-align: center;
    font-size: 20px;
    color: white;
}
.colorbackground h1{
    background-color: red;
    display: inline-block;
    padding: 0 1em 0;
}
<!DOCTYPE HTML>
<html>
    
<head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Background Color Test</title>
    
    <link rel="stylesheet" href="style.css">
    
</head>
       
<body>
    
    <div class=colorbackground>
    
        <h1>Hello World!</h1>
        
    </div>       
    
</body>

</html>
Musa
  • 96,336
  • 17
  • 118
  • 137
0

You can add span to wrap your text

body {
    background-color: darkslateblue;
}
.colorbackground{
    text-align: center;
    font-size: 20px;
    color: white;
}
h1 span { 
    background-color: red;
}
<!DOCTYPE HTML>
<html>
    
<head>
    
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    
    <title>Background Color Test</title>
    
    <link rel="stylesheet" href="style.css">
    
</head>
       
<body>
    
    <div class=colorbackground>
    
        <h1><span>Hello World!<span></h1>
        
    </div>       
    
</body>

</html>
Pterrat
  • 1,682
  • 11
  • 18