This image should be self explanatory.

Basically, I'm trying to have a div behaving as follows:
If CSS can't do this alone, do you have a link to similar working JS ?
JSFiddle that I'm trying to use to figure out: https://jsfiddle.net/375fmu1q/164/
<div class="outer-div">
<div class="inner-div">
<div class="part1">
This is part 1 -
</div>
<div class="part2">
This is part 2 -
</div>
<div class="part3">
This is part 3 -
</div>
<div class="part4">
This is part 4
</div>
</div>
</div>
One way you can do this by direction:rtl Refer : Here
With Flexbox using flex-flow: row-reverse;
body {margin:0;}
.outer-div {
white-space:nowrap;
overflow: hidden;
display: flex;
flex-flow: row-reverse;
max-width: 400px;
}
.inner-div {
display:flex;
}
.part {
padding: 10px;
}
.part1 {
background-color:red;
}
.part2 {
background-color:blue;
}
.part3 {
background-color:green;
}
.part4 {
background-color:yellow;
}
<div class="outer-div">
<div class="inner-div">
<div class="part part1">
This is part 1
</div>
<div class="part part2">
This is part 2
</div>
<div class="part part3">
This is part 3
</div>
<div class="part part4">
This is part 4
</div>
</div>
</div>
There is one possible solution to your problem. This requires both CSS and JS to work. The outer and inner div should have the following understanding:
.outer-div {
position: relative;
// padding-top: <height of .inner-div>
}
.inner-div {
position: absolute;
left: 0;
top: 0;
}
This will have the same effect as float: left. This is how the styles should work during normal size, i:e .outer-div width is greater than the .inner-div width. Now we are going to write a JS code that will detect if this condition has changed and apply the difference as negative left to achieve your desired effect.
const onResizeOrDetectChange = () => {
const outerDiv = document.querySelector('.outer-div');
const innerDiv = document.querySelector('.inner-div');
const widthDiff = outerDiv.offsetWidth - innerDiv.offsetWidth
// will be less than 0 when outer div width is less than inner div width
if (widthDiff < 0) {
innerDiv.style.left = widthDiff + 'px'
} else {
innerDiv.style.left = 0
}
}
Call onResizeOrDetectChange when screen resize or any event where you would like to adjust and it can produce the desired effect you are looking for.
Here is the modified fiddle: https://jsfiddle.net/o7m7bo60/8/. I have used flex-box styling as compared to your float: left to make the .inner-div stay in one line
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With