How to make nested div scrollable when parent is too small on x axis?

2.6k views Asked by At

I'm trying to have a nested div with a fixed width inside a parent div with a relative width.

The point is, the nested div should always have a fixed width. In case the parent has a smaller width, the nested should have a x-scrollbar and so its visible part would be smaller than its fixed width.

The jsFiddle will help : https://jsfiddle.net/ycLvc2c8/1/

HTML

<div class="parent">
    <div class="nested">
    012345678901234567890123456789z // 31 ch long
    </div>
</div>

CSS

.parent {
    background-color: red;
    height: 100px;
    padding-top: 10px;
    width: 70%;
}

.nested {
    width: 30ch;
    max-width: 100%;
    overflow-x: scroll;
    background-color: orange;
    font-family: monospace;
}

What I'd like is that the final 'z' should always be written on a second line because the nested div should be 30characters long. when you reduced the window width, the visible part of the nested will be smaller but still, the 'z' should be on the second line, all the digits on the first line with a scrollbar.

I hope this is clear enough :)

Thanks for your help

3

There are 3 answers

0
Pasquale Muscettola On BEST ANSWER

Is this what are you looking for?

.parent {
    background-color: red;
    height: 100px;
    padding-top: 10px;
    overflow-x: scroll;
    width: 70%;
}

.nested {
    width: 30ch;
    background-color: orange;
    font-family: monospace;
    word-wrap: break-word;
}

https://jsfiddle.net/r39woave/

0
jaunt On

If I've interpreted this correctly, simply add word-break: break-word; to the .nested CSS to force the 'z' onto a new line.

0
youngwind On

The method jaunt said can solve the punctuate problem, however it's still another problem.

If the width of the parent div is too small(for example width=20%), it will display like this we can see that numbers will be display in second line

so, I improved the method https://jsfiddle.net/ycLvc2c8/3/

.parent {
    background-color: red;
    height: 100px;
    padding-top: 10px;
    width: 20%;
    overflow:scroll;
}
.nested {
    width: 30ch;
    /* max-width: 100%; */
    /* overflow-x: scroll; */
    background-color: orange;
    font-family: monospace;
    word-break: break-word;
}

hope it helps.