Blackbam
Blackbam

Reputation: 19396

CSS: Make inner div 100% body width without using position:absolute - is it possible?

Lets assume for some reason I can not change the HTML, neither use JavasScript. Lets assume the position of #content_actual depends on the height of #element. #element has a flexible height.

Is there a solution for this problem?

HTML:

<div id="content">
  <div id="element">ABCDE</div>
  <div id="content_actual">FGHIJ</div>
</div>

CSS:

#content {
  width:960px;
  margin: 0 auto;
}

#element {
// width: 100% of body width
// position: everything but position absolute or fixed
}

Upvotes: 2

Views: 1519

Answers (2)

Paulie_D
Paulie_D

Reputation: 115293

A combination of relative positioning, viewport units and calc.

Codepen Demo

NOTE: this breaks as soon as the viewport is less than the container width. Media queries would be required at that point.

#content {
  width: 480px; /* numbers changed for this Snippet */
  margin: 0 auto;
  background: green;
  padding: 50px;
}
#element {
  height: 50px;
  line-height: 50px;
  width: 100vw;
  position: relative;
  right: calc(50vw - 240px); /* second value 50% of container width */
  background: lightblue;
}
<div id="content">
  <div id="element">ABCDE</div>
  <div id="content_actual">FGHIJ</div>
</div>

It should also be noted that the container cannot have overflow:hidden for this technique to work.

Upvotes: 1

Chris
Chris

Reputation: 2646

Similar to Paulie_D's (apparently we were sharing brainwaves) but this uses percentage to counter the container width. No idea how well supported this would be:

https://jsfiddle.net/7w2cwqfq/4/

<div id="content">
  <div id="element">ABCDE</div>
  <div id="content_actual">FGHIJ</div>
</div>

#content {
width:200px;
margin: 0 auto;
background: yellow;
}

#element {
  position: relative;
  left: calc(-50vw + 50%);
  width: 100vw;
  background: red
}

Upvotes: 2

Related Questions