DJAy
DJAy

Reputation: 330

Make div background 100% as much as window width

I have div content-3 which is inside container. I want to make this background color 100% for his height which may increase. I think this possible using css. Here is image of my requirement. enter image description here

*{padding:0; margin:0; box-sizzing:border-box;}
.container{margin: 0px auto; width: 80%; border: 1px solid #333;}
.content{min-height:50px}
.content-3{background:green}
<div class="container">
<div class="content content-1">content 1</div>
<div class="content content-2">content 2</div>
<div class="content content-3">content 3</div>
<div class="content content-4">content 4</div>
</div>

Upvotes: 1

Views: 75

Answers (3)

Michael Mason
Michael Mason

Reputation: 932

As an alternative answer you could use the :before and :after pseudo-elements to achieve the same effect.

No changes to the HTML.

Add this to your CSS:

.content.content-3 {
    position: relative;
}
.content.content-3:before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: -10vw;
    right: 100%;
    background: green;
}
.content.content-3:after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    left: 100%;
    right: -10vw;
    background: green;
}

Edit: Changed -100% to -10vw for left/right positions. vw means viewport width so given your container is 80% wide, you want each side to extend 10vw to make the full 100% with no horizontal scrolling.

Upvotes: 1

Michael Mason
Michael Mason

Reputation: 932

If you're able to create multiple container elements you could do something like:

<div class="container">
    <div class="content content-1">content 1</div>
    <div class="content content-2">content 2</div> 
</div>
<div class="container-wrapper">
    <div class="container">
        <div class="content content-3">content 3</div>
    </div>
</div>
<div class="container">
    <div class="content content-4">content 4</div>
</div>

Then just make container-wrapper full-width with a green background.

Upvotes: 0

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11121

As a visual trick, you can add extra padding to the div and counteract using negative margins. However you have to add overflow-x:hidden to body to prevent horizontal scroll:

*{padding:0; margin:0; box-sizzing:border-box;}
.container{margin: 0px auto; width: 80%; border: 1px solid #333;}
.content{min-height:50px}
.content-3{
  background:green;
  padding-left:100%;
  padding-right:100%;
  margin-left:-100%;
  margin-right:-100%;
}

body{overflow-x:hidden}
<div class="container">
<div class="content content-1">content 1</div>
<div class="content content-2">content 2</div> 
<div class="content content-3">content 3</div>
<div class="content content-4">content 4</div>
</div>

Upvotes: 1

Related Questions