只使用css更改顺序和定位 [英] Change order and positioning using only css
问题描述
如何使用媒体查询更改div中的元素顺序和位置?
下图显示了所需的行为(当浏览器窗口小于1000像素宽时,使用左图像,第二个较大时使用左图像):
How I can change element order and positions within a div using media queries? The following image shows the desired behaviour(use left image when browser window is smaller than 1000px wide, the second when bigger.):
我第一次尝试在第一种情况下使用正常第二个使用float:
My first attempt using 'normal' placement on first case and use float on the second:
.box2 {
float: right;
}
但是元素2(绿色)不接近第一个元素。
but then the element 2 (green) aligns on extreme right of container. Not close to the first element.
fiddle: http ://jsfiddle.net/vmkRM/1/
推荐答案
假设您有标准HTML,如下所示:
Assuming you have standard HTML that looks like this:
<div id=outer>
<div id=box1></div>
<div id=box2></div>
</div>
像这样的CSS:
#box1 {
width: 150px;
height: 50px;
background-color: green;
margin: 10px;
}
#box2 {
width: 200px;
height: 100px;
background-color: orange;
margin: 10px;
}
我会通过添加这个CSS实现窄版本:
I'd achieve the narrow version by adding this CSS:
#box1, #box2 {
margin-left: auto;
margin-right: auto;
}
我通过添加这个CSS来实现宽版本:
And I'd achieve the wide version by adding this CSS instead:
#outer {
float: left;
}
#box1, #box2 {
float: right;
}
#box1 {
margin-top: 35px;
}
注意,我是通过手动计算额外的顶部以便垂直对齐框。
Note that I'm cheating a bit by manually calculating the extra top-margin in order to vertically align the boxes.
将所有的媒体查询结合在一起会自动执行以下操作:
Putting it all together with media queries to do it automatically would look like this:
#box1 {
width: 150px;
height: 50px;
background-color: green;
margin: 10px auto 10px auto;
}
#box2 {
width: 200px;
height: 100px;
background-color: orange;
margin: 10px auto 10px auto;
}
@media (min-width: 450px) {
#outer {
float: left;
}
#box1, #box2 {
margin: 10px;
float: right;
}
#box1 {
margin-top: 35px;
}
}
一个工作的小提琴就在这里: http://jsfiddle.net/UwtZW/
(请注意,我使用较窄的宽度工作在小提琴工作 - 但它应该很容易适应你需要的实际宽度)
A working fiddle is here: http://jsfiddle.net/UwtZW/
(Note that I've used narrower widths to make it work nicely in the fiddle - but it should be easy to adapt to the actual widths you need)
如果有人知道如何自动实现垂直对齐而不知道高度,我会很有兴趣学习。当我尝试,我不能超过浮动/垂直对齐冲突。
If anybody knows how to achieve the vertical alignment automatically without knowing the heights, I'd be very interested to learn. When I try, I can't get past the float / vertical-alignment conflict.
这篇关于只使用css更改顺序和定位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!