【问题标题】:How to add responsiveness to a flexbox div element without a css file如何在没有 css 文件的情况下为 flexbox div 元素添加响应性
【发布时间】:2021-03-24 09:06:11
【问题描述】:
正如标题所暗示的,我一直想知道是否可以在不使用外部 css 文件的情况下为 div flexbox 元素添加响应性,而是将其直接放入 div 样式中。我的代码如下所示,在桌面版本上,文本应位于图像的右侧,但在移动/平板电脑版本中,我想将其放在图像下方。我如何添加响应能力,因为现在它在移动设备上查看时会溢出元素。
<div style="display: flex; flex-direction: row; flex-wrap: wrap; margin-bottom: 20px;">
<img src="image on the left side">
<div style="flex-direction: column;">
<b>title to the right of the image</b>
<p>description under title</p>
</div>
</div>
【问题讨论】:
标签:
html
css
flexbox
responsive-design
media-queries
【解决方案1】:
媒体查询使用@media 规则添加CSS 属性,而according to MDN:
@media CSS at 规则可用于根据一个或多个媒体查询的结果应用样式表的一部分。使用它,当且仅当媒体查询与使用内容的设备匹配时,您指定一个媒体查询和一个 CSS 块以应用于文档。
因此,如果没有 <head></head> 中的内部 <style></style> 标记或单独的样式表文件,就不可能使用它。
【解决方案2】:
“没有外部 CSS 文件”:是的,通过将相应的 CSS 规则放在 HTML 文档本身的 <style></style> 标记中(最好在 <head> 中,但它也适用于 body)
例子:
<style>
.a {
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-bottom: 20px;
}
.b {
display: flex;
flex-direction: column;
}
@media screen and (max-width: 600px) {
.a {
flex-direction: column;
}
}
</style>
<div class="a">
<img src="https://placehold.it/300x200/fa0">
<div class="b">
<b>title to the right of the image</b>
<p>description under title</p>
</div>
</div>
【解决方案3】:
min-width 和 flex-grow 可能是一个提示:
<div
style="
display: flex;
flex-direction: row;
flex-wrap: wrap;
margin-bottom: 20px;
">
<img src="https://dummyimage.com/300x100/f5a"
style="
flex-grow:1;
min-width:320px;
">
<div
style="
display:flex;
flex-direction: column;
flex-grow:1;
background:lightgray;
min-width: 60%;
justify-content:center;
padding:0.5em;
">
<b>title to the right of the image</b>
<p>description under title</p>
</div>
</div>