Search code examples
csscss-positiontailwind-css

Background color of parent-div from left side of screen to right edge of text


I'm trying to accomplish something like this:

enter image description here

The heading text has a max width of 64rem and it's parent div is horizontally centered with margin-right and -left set to auto.

The paragraph text below is a bit more narrow and has a max-width of 56rem and is also horizontally centered.

Setting the text like this works fine. My problem is, that I don't know how to set the parent-div which wraps around those two texts. The div has a background color and it should go from the left side of the screen to the right edge of the paragraph text.

My code looks like this:

.parent-div {
    background-color: #907272;
    ???
}
 
 .heading-div {
    max-width: 64rem;
    margin-left: auto;
    margin-right: auto;
}
  
.paragraph-div {
    max-width: 56rem;
    margin-left: auto;
    margin-right: auto;
}
<div class='parent-div'>
    <div class='heading-div'>
      <h2>This is a heading.</h2>
    </div>
    <div class='paragraph-div'>
      <p>Lorem ipsum sit dolor...</p>
    </div>
 </div>

Important note: I am working with tailwindcss classes. I wrote the sample code in plain css for better understanding.

My main question is: How do I set the parent-div, that it goes from the left side of the screen to the right edge of the paragraph text?


Solution

  • I would consider a gradient coloration to avoid messing with other stuff:

    .parent-div {
      overflow: auto;
      background:
       linear-gradient(-90deg,
       #0000 calc(50vw - 56rem/2),
       #907272 0); 
    }
    
    .heading-div {
      max-width: 64rem;
      margin: auto;
      outline: 1px solid green;
    }
    
    .paragraph-div {
      max-width: 56rem;
      margin: auto;
      outline: 1px solid red;
    }
    
    body {
      margin: 0;
    }
    <div class='parent-div'>
      <div class='heading-div'>
        <h2>This is a heading.</h2>
      </div>
      <div class='paragraph-div'>
        <p>Lorem ipsum sit dolor...</p>
      </div>
    </div>

    Another solution is to apply the coloration to the paragraph element

    .parent-div {
      overflow: auto;
    }
    
    .heading-div {
      max-width: 64rem;
      margin: auto;
      outline: 1px solid green;
    }
    
    .paragraph-div {
      max-width: 56rem;
      margin: auto;
      outline: 1px solid red;
      border-image: conic-gradient(#907272 0 0) fill 0//100vh 0 20px 100vw;
    }
    
    body {
      margin: 0;
    }
    <div class='parent-div'>
      <div class='heading-div'>
        <h2>This is a heading.</h2>
      </div>
      <div class='paragraph-div'>
        <p>Lorem ipsum sit dolor...</p>
      </div>
    </div>