如何实现 css 布局随着屏幕宽度变化?-灵析社区

销售经理537

我的需求:css 使用 flex 帮我实现一个效果:左侧是一个图片,设置宽高为 200x200,右侧是一段文本;然后当在大尺寸的屏幕上,让右边的文本边充满右侧;但是如果在小尺寸的屏幕上,比如手机,那么让图片显示在上面;文本显示在下面 chatGPT 给了我下面的代码 Flexbox Example .container { display: flex; flex-direction: row; /* 默认水平布局 */ } .image { width: 200px; height: 200px; background-color: #f0f0f0; margin-right: 20px; /* 图片和文本之间的间距 */ } .text { flex: 1; /* 右侧文本占据剩余空间 */ } /* 在小尺寸屏幕上媒体查询 */ @media screen and (max-width: 600px) { .container { flex-direction: column; /* 垂直布局 */ } .image { margin-bottom: 20px; /* 图片下方留出间距 */ } } Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed consequat placerat lorem. 但是渲染出来的布局效果并不会随着屏幕宽度而变化 ![图片.png](https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241025/43e8f1887e9c566f60a53a19c0c1be6d.png) 只会等比例变化,为什么? ![图片.png](https://wmlx-new-image.oss-cn-shanghai.aliyuncs.com/images/20241025/29a2609a31401d1f1188383b00d7813f.png) 如何实现 css 布局随着屏幕宽度变化?

阅读量:101

点赞量:0

问AI
"" 要加一句 完整的如下: Flexbox 布局示例 .container { display: flex; } .image { width: 200px; height: 200px; } .text { flex: 1; } /* 在小尺寸设备上,重置布局 */ @media (max-width: 600px) { .container { flex-direction: column; /* 将布局改为垂直方向 */ } .image { width: 200px; height: 200px; } .text { width: auto; /* 让元素宽度自适应 */ height: auto; /* 让元素高度自适应 */ } /* 取消 .text 的 flex 属性 */ .text { flex: initial; /* 或者可以使用 flex: none; */ } } 图片 文本