Reputation: 15006
I have for divs:
<div id="1"></div>
<div id="2"></div>
<div id="3"></div>
<div id="4"></div>
On desktop, they are positioned like this:
1
2
3
4
On mobile, I would like them to be positioned like this:
1 3
2 4
if i do
div{
width: 50%;
float: left;
clear left;
}
#3,#4{
float: right;
clear: right;
}
They end up like this:
1
2 3
4
The divs are dynamically generated, so if I can avoid adding additional markup, that would be very good.
Upvotes: 0
Views: 415
Reputation: 10240
I know this has been answered, but I thought I'd give you a different perspective and actually a more commonly used one as well. If you apply bootstrap framework (even if not to a global extend) but you can gut out the css the is valid to your problem, you will be able to do this a lot more comfortably. without getting into css specifity. All you have to do is make proper us of col-md-12
and col-xs-6
See DEMO
Upvotes: 1
Reputation: 71150
Given the HTML
<div class='wrapper'>
<div id="1">1</div>
<div id="2">2</div>
<div id="3">3</div>
<div id="4">4</div>
</div>
You could use the CSS:
.wrapper > div {
border:1px solid; /* <-- not needed, used to show div locations */
height:100px; /* <-- not needed, used to show div locations */
}
@media screen and (max-width: 300px) { /* <-- apply styles on certian screen size */
.wrapper {
-webkit-column-count:2; /* <--put the divs in two columns */
-moz-column-count:2; /* <--put the divs in two columns */
column-count:2; /* <--put the divs in two columns */
}
}
Changing the 300px
for whatever you deem a mobile device screen to be
Upvotes: 4
Reputation: 2398
Another approach would simply use media queries to change the width of the divs. This would allow you to avoid adding more markup.
http://jsfiddle.net/14ecjy7n/1/
div {
box-sizing: border-box;
float: left;
}
@media all and (max-width: 639px) {
div {
width: 50%;
}
}
@media all and (min-width: 640px) {
div {
width: 100%;
}
}
Upvotes: 0