skip to Main Content

A div will take up the entire row. But let’s suppose that the content, text, only goes up to 50% of the row. How to specify that the background should only go up to 50% of the row of the div, where the content lives?

IE where there is no content, the background should be transparent?

2

Answers


  1. To specify that the background of a <div> should only go up to 50% of the row where the content lives, you can use CSS to control the background size and positioning. You’ll want to create a container <div> to hold both the content and the background, and then apply styles to achieve this effect. Here’s how you can do it:

    HTML

    <div class="container">
      <div class="content">
        <!-- Your content goes here -->
        <p>This is some content.</p>
      </div>
    </div>
    

    CSS

      /* Style for the container div */
      .container {
        width: 100%; /* Make the container span the entire row */
        background-color: #f0f0f0; /* Set the background color for the entire row */
      }
    
      /* Style for the content div */
      .content {
        width: 50%; /* Set the width of the content to 50% of the container */
        margin: 0 auto; /* Center the content horizontally within the container */
        padding: 20px; /* Add some padding for spacing */
        background-color: white; /* Set the background color for the content area */
      }
    

    In this example, we have a .container div that spans the entire row and has a background color that covers the entire row. Inside the container, we have a .content div with a width of 50% of the container’s width. This .content div contains your text or content.

    By setting the background color of the .content div to white (or any color you prefer), you ensure that the background only covers the content area, which is 50% of the row. Adjust the background colors and other styles to match your design preferences.

    Login or Signup to reply.
  2. Just wrap your content into an element with display:inline-block;background: your-background-here:

    .content>*{
      display:inline-block;
      background: lightpink;
      padding: 5px 10px;
    }
    .content{
      border: 1px solid lightgray;
    }
    <div class="content">
    <span>Lorem ipsum dolor sit amet, consectetur adipiscing</span>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search