Solution 1 :

You can achieve this by wrapping you text in a span like this and adding the color to span.

.parent {
  width: 400px;
  max-width: 400px;
  overflow: scroll;
}

.child {
  white-space: nowrap;
  display:table-row;
  background: skyblue;
}
<div class="parent">
  <div class="child">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.
  </div>
  <div class="child">second child</div>
  <div class="child">third child</div>
</div>

EDIT:
Just add display:table to child class, it will work

Problem :

I want to have a child div with text on one line, with a background color that covers the whole line, inside a parent div with a max-width and be able to scroll along the x-axis.

The background color must be on the child element because the children(there are multiple children) will have different colors. All child elements must have the same width.

I only want to use CSS and no hard coded numbers on the child element.

My problem is that the child element doesn’t cover the whole line, you can see the problem when you scroll horizontally.

To reproduce my issue:

.parent {
  width: 400px;
  max-width: 400px;
  overflow: scroll;
}

.child {
  white-space: nowrap;
  background: skyblue;
}

<div class="parent">
  <div class="child">
     Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. 
     Aenean massa. 
  </div>
  <div class="child">second child</div>
  <div class="child">third child</div>
</div>

or https://codepen.io/alawiii521/pen/rNObXrm

Comments

Comment posted by Amit Pandey

Please select it accepted, if it works for you the way you want.

Comment posted by Ali Majed

Thanks for the answer! I updated my question, it wasn’t clear that there are multiple children and all must have the same width. This solution did not work when you have multiple children

Comment posted by Ali Majed

One of the requirement in my question says “All child elements must have the same width”, this requirement is not met. To clarify, all the children must have the same width as the parent div

Comment posted by Amit Pandey

I defiantly missed that, updated the code again, this should be final i guess.

By

Leave a Reply

Your email address will not be published. Required fields are marked *