最接近纯 CSS 的是 Flexbox,但浏览器支持仅限于那些支持换行的浏览器(请参阅: http ://caniuse.com/flexbox,IE10 是唯一支持部分支持换行的浏览器)。目前该列表仅限于 IE10、Opera 和 Chrome。
http://codepen.io/cimmanon/pen/fqoxj
假设您的标记看起来像这样:
<header>
Header
</header>
<nav>
Nav
</nav>
<main>
<figure>
<img src="http://placekitten.com/200/200" width="200" height="200" />
<figcaption>What a cute kitten</figcaption>
</figure>
<figure>
<img src="http://placekitten.com/200/200" width="200" height="200" />
<figcaption>So adorable!</figcaption>
</figure>
<figure>
<img src="http://placekitten.com/200/200" width="200" height="200" />
<figcaption>Irresistibly cuddly</figcaption>
</figure>
</main>
CSS将是这样的:
body {
display: -ms-flexbox;
display: -webkit-flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
@supports (flex-wrap: wrap) {
body {
display: flex;
}
}
header {
background: yellow;
-webkit-flex: 1 100%;
-ms-flex: 1 100%;
flex: 1 100%;
}
nav {
background: orange;
-webkit-flex: 1 15em;
-ms-flex: 1 15em;
flex: 1 15em;
}
main {
-webkit-flex: 3 30em;
-ms-flex: 3 30em;
flex: 3 30em;
/* everything below this line is all that really matters
* everything above this line is controlling the main layout */
display: -ms-flexbox;
display: -webkit-flex;
-webkit-flex-wrap: wrap;
-ms-flex-wrap: wrap;
flex-wrap: wrap;
}
@supports (flex-wrap: wrap) {
main {
display: flex;
}
}
figure {
display: inline-block; /* fallback for old browsers */
/* note that the images are 200px wide, this has to match or Chrome does weird stuff */
-webkit-flex: 1 200px;
-ms-flex: 1 200px;
flex: 1 200px;
}
figure img {
min-width: 100%;
height: auto;
}
对于移动设备,一旦您缩放到导航不再位于侧面的位置,您就可以安全地使用媒体查询来控制图像的大小:
http://cssdeck.com/labs/l2hw4aon
figure {
display: inline-block;
}
figure img {
max-width: 100%;
height: auto;
}
@media (max-width: 40em) {
figure {
width: 30%;
}
}
@media (max-width: 30em) {
figure {
width: 45%;
}
}
@media (max-width: 20em) {
figure {
width: 100%;
}
}