I have a container with 1000px width. On of the design items has a background of full-width (see blue bar on the image). Is it possible to put such background without additional markup?
Here's how it looks like:
And the markup I'd like to use:
<div class="container">
<p>Lorem...</p>
<p class="bar">Lorem</p>
<p>Lorem...</p>
<p>Lorem...</p>
<p>Lorem...</p>
</div>
I tried to do it with absolutely positioned additional element and some extra tricks, like this:
.bar:after {
position: absolute;
top: 0;
left: 50%;
width: 100vw;
height: 100%;
background-color: blue;
transform: translateX(-50%);
z-index: -1;
}
It's almost good enough, except there's a problem to get it at the top of the container and not at the top of the contents of the blue bar. Plus, using extra element feels redundant.
It also can be done by placing the blue bar outside of the container, as parent and a child, but this way I will end up putting the 1000px value three times: for the div above the blue one, for the div inside blue one and for the div under the blue one.
Is there some way to achieve this effect to avoid repeating container's width and without any additional markup?
Here is CSS
calc()
approach. Since the container is fixed width, so you can use negative margin to make.bar
full viewport width, and use same amount of positive padding for the correction of the vertical alignment of the text box (optional).I put it into a media query make sure to check it out in a larger window.
Codepen
Previous answer