FunkySayu FunkySayu - 2 months ago 10
CSS Question

Set element width to 100% scrollable width

I am facing a layout issue with CSS where I cannot set an element attribute to the maximum scrollable width. In my situation, I have a relative sized div (in real code, it is supposed to be responsive) showing text inside. The objective is to set a background color to some lines in order to underline difference.

<div id="wrapper">
<span class="green"> That's an add ! Scroll me...
</span>
<span>Lorem ipsum dolor sit amet blablablablablablabl
</span>
</div>


Here is a JSFiddle I made to illustrate.

#wrapper {
width: 25%;
overflow-x: scroll;
}

span {
white-space: pre; /* required */
font-family: monospace; /* required */
display: block; /* required to make width effective */
width: 100%;
}

.green {
background-color: #7f7;
}


I cannot set the background color to the end of the block, which means that if someone scroll, he will not see the color.

There are several questions like that on Stackoverflow and many suggest using a
min-width
value (i.e. background css 100% width horizontal scroll issue). Thing is it is not that good if the content does not reach the
min-width
value.

If there is a proper way to fix this, I would be glad to hear it !

Answer

Use vw (100% viewport width) to stretch the container to the end of viewport. You also need to change your display to table-header-group:

span {
  white-space: pre;  /* required */
  font-family: monospace;  /* required */
  display: table-header-group;  /* required to make width effective */
  width: 100vw; /*100% of viewport width*/
}

vh (viewport height) can also be used in cases you need to stretch the container to 100% of viewport height.

Hope it helps.

Comments