Search code examples
htmlcssbackground-colorcontact-form

Making div background less than 100% width in CSS?


I have simple contact form, but I'd like it to have a bit of a background around it. However, simply putting background-color doesn't work how I would like it to. The background color is the full width of the page, but I only want it to cover a small area around the contact form. I've put a picture as to something along the lines of what I'd like it to look like. Example of what is required HTML:

<div class="contact">
    <form action="/action_page.php">
        <input type="text" id="fname" name="firstname" placeholder="Your name"><br>
        <input type="text" id="lname" name="lastname" placeholder="Your last name"><br>
        <textarea rows="10" placeholder="Type Message"></textarea><br>
        <input type="submit">
    </form>
</div>

CSS

    .contact {
    text-align: center;
    background-color: #E0E0E0;
}

input[type=text] {
    width: 20%; 
    padding: 6[enter image description here][1]px; 
    border: 1px solid #ccc; 
    border-radius: 4px; 
    box-sizing: border-box; 
    margin-top: 6px; 
    margin-bottom: 16px; 
}

textarea {
    width: 45%; 
    padding: 6px; 
    border: 1px solid #ccc; 
    border-radius: 4px; 
    box-sizing: border-box; 
    margin-top: 6px; 
    margin-bottom: 16px; 
}

input[type=submit] {
    background-color: #4CAF50;
    color: white;
    padding: 12px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

input[type=submit]:hover {
    background-color: #45a049;
}

Solution

  • What about putting everything inside a container and adding some margins?

    HTML

    <div class="container">
      <div class="contact">
          <form action="/action_page.php">
              ...
          </form>
      </div>
    </div>
    

    CSS

    .contact {
        text-align: center;
        background-color: #E0E0E0;
        margin: 0px 50px 20px 50px;
    }
    

    Then you can use the container css to adapt it to the context.