HTML5/CSS 不是我的强项之一。我有一个简单的要求 - 三个 DIV 根据屏幕尺寸进行不同的布局,为此我使用 @media 声明。
Layout 1 Layout 2
+----- container -----------------+ +----- container ---------------------+
| +-----------------------------+ | | +------------+ +-----------------+ |
| | header text | | | | thumbnail | | header text | |
| +-----------------------------+ | | | image | +-----------------+ |
| +------------+ +-------------+ | | | | +-----------------+ |
| | thumbnail | | body text | | | +------------+ | body text body | |
| | image | | body text | | | | text body text | |
| | | | body text | | | | body text ..... | |
| +------------+ +-------------+ | | +-----------------+ |
+---------------------------------+ +-------------------------------------+
基本标记是:
<div id="container">
<div id="header">header text</div>
<div id="thumbnail"><a href="xxx"><img src="yyy" /></a></div>
<div id="bodytext">Some free-form text to be wrapped</div>
</div>
缩略图是固定大小的。到目前为止,我的努力是:
布局 1 对 thumbnail
和 bodytext
div 使用 float:left。
布局 2 使用 padding-left: [image width]px;在 header
和 bodytext
div 上,以及 thumbnail
的绝对定位。
但这一切都让人觉得不对劲,而且我担心跨浏览器/设备实现的脆弱性。
是否有更适合用途的东西,例如 flex ?
最佳答案
您可以使用 CSS Grid解决方案。请全屏查看以获取解决方案。玩Grid Generator .
#container {
display: grid;
grid-template-columns: 1fr 1fr;
grid-template-rows: 1fr 1fr;
grid-column-gap: 10px;
grid-row-gap: 10px;
}
#header {
grid-area: 1 / 1 / 2 / 3;
}
#thumbnail {
grid-area: 2 / 1 / 3 / 2;
}
#bodytext {
grid-area: 2 / 2 / 3 / 3;
}
@media (max-width:600px) {
#header {
grid-area: 1 / 2 / 2 / 3;
}
#thumbnail {
grid-area: 1 / 1 / 2 / 2;
}
#bodytext {
grid-area: 2 / 2 / 3 / 3;
}
}
/* Extra Styling for Snippet */
#container > div { background: #5548B0; color: #fff; text-align: center; font-size: 2em; padding: 5%; }
<div id="container">
<div id="header">Header Text</div>
<div id="thumbnail">
<a href="stackoverflow.com"><img src="https://loremflickr.com/320/240"></a>
</div>
<div id="bodytext">Some free-form text to be wrapped</div>
</div>
关于html - 需要 CSS 帮助 - 媒体查询阻止布局变化 - flex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57450412/