我有
HTML标记,包含三个div:
<div class="gallery">Gallery</div> <div class="content">Content</div> <div class="sidebar">Sidebar</div>
我想使用CSS以两种不同的布局呈现它(如果我可以控制侧边栏是左侧还是右侧,那就更好了):
+------------------+ | Gallery | +------+-----------+ | Side | Content | | | | +------+-----------+ +------+-----------+ | Side | Gallery | + +-----------+ | | Content | | | | +------+-----------+
事实上,如果我可以控制侧边栏是左侧还是右侧,那就更好了.
只要内容出现在侧边栏之前,我就可以添加额外的div和/或更改div的源顺序.但是不能在每个布局的基础上更改HTML.
这是我使用flexBox order属性解决问题的不完整尝试.
/* for demonstration */ .gallery { height: 100px; background-color: #CCC; } .content { height: 200px; background-color: #EEE; } .sidebar { height: 150px; background-color: #AAA; } /* common */ .middle { display: flex; flex-direction: row; flex-wrap: wrap; } /* layout-1 */ .middle.layout-1 .gallery { order: 1; width: 100%; } .middle.layout-1 .content { order: 3; width: 75%; } .middle.layout-1 .sidebar { order: 2; width: 25%; } /* layout-2 */ .middle.layout-2 .gallery { order: 2; width: 75%; } .middle.layout-2 .content { order: 3; width: 75%; } .middle.layout-2 .sidebar { order: 1; width: 25%; }
<div class="middle layout-1"> <div class="gallery">Gallery</div> <div class="content">Content (this layout works perfectly)</div> <div class="sidebar">Sidebar</div> </div> <hr> <div class="middle layout-2"> <div class="gallery">Gallery</div> <div class="content">Content (should go below gallery)</div> <div class="sidebar">Sidebar</div> </div>
解决方法
通常我会避免像瘟疫这样的漂浮物,但在这种情况下,它们可以满足您的需要.
如果要切换侧边栏的侧面,只需交换左侧和右侧.
这将使您的布局保持动态大小的内容:
.gallery { background: red; } .content { background: green; } .sidebar { background: blue; } /* layout1 */ .layout1 .gallery { width: 100%; } .layout1 .content { width: 75%; float: right; } .layout1 .sidebar { width: 25%; float: left; } /* layout2 */ .layout2 .gallery { width: 75%; float: right; } .layout2 .content { width: 75%; float: right; } .layout2 .sidebar { width: 25%; }
<div class="layout1"> <div class="gallery">Gallery</div> <div class="content">Content</div> <div class="sidebar">Sidebar</div> </div> <br> <br> <br> <div class="layout2"> <div class="gallery">Gallery</div> <div class="content">Content</div> <div class="sidebar">Sidebar</div> </div>