Reputation: 4409
Is there a way to display 3 elements in a single line when space available for all the 3 and if not, display each of them in a single separate row?
So if i can show 3 inline ok, but I'd like to avoid 2 elements in a row and the last in the next row. The requisite is to preferably NOT use media query.
Upvotes: 0
Views: 64
Reputation: 67778
You can do it with Javascript or jQuery as below. It gets the width of each element. If the sum of these is more than the width of the wrapper element, it converts the elements from display: inline-block
to display: block
, thereby making them 100% wide:
$(document).ready(function() {
var L1 = $(".x1").width();
var L2 = $(".x2").width();
var L3 = $(".x3").width();
var sum = L1 + L2 + L3;
var availableSpace = $(".wrapper").innerWidth();
if (availableSpace < sum) {
$(".x").css('display', 'block');
};
})
body,
html {
margin: 0;
}
.x {
display: inline-block;
padding: 10px;
border: 1px solid #bbb;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="x x1">11111111111 11111111111111 11111111111111</div><div class="x x2">2222222222222 2222222222222 222222222222</div><div class="x x3">333333333333 333333333333333333</div>
</div>
Make the snippet fullscreen to see the effect. Instead of the .wrapper
DIV you could also just use body
in the jQuery function, if you don't have a parent element around those three elements.
Upvotes: 1