如何根据浏览器窗口宽度居中并重排表格内带标题的图片
问题原因
- 你当前使用
flex-wrap: wrap配合flex-basis: auto实现自动换行,不同行的文字内容宽度不同,导致各行触发换行的屏幕阈值不一致,就会出现部分行折叠、部分行没折叠的错位效果。 - 你靠手动交换HTML中td的顺序实现图文交替排列,小屏折叠为单列时会直接继承HTML的节点顺序,导致偶数行的文字出现在图片上方。
实现方案
我们通过固定阈值的媒体查询实现所有行同步折叠,通过flex的order属性控制图文排序,不需要手动修改HTML结构,同时满足大屏交替排列、小屏统一图片在上的要求。
第一步:统一HTML结构
所有行的td都固定为「图片在前,文字在后」,不需要手动交换顺序:
<div class="section__article_center"> <table class="section-article__table"> <thead>Some photos</thead> <tbody> <tr> <td><img src="你的图片地址" alt="Some photo"></td> <td>Beautiful clouds</td> </tr> <tr> <td><img src="你的图片地址" alt="Some photo"></td> <td>Wet water</td> </tr> </tbody> </table> </div>
第二步:修改CSS样式
:root { --text-white: #fff; --table-image-width: 500px; --fold-threshold: 1160px; /* 折叠阈值,计算逻辑:(图片宽度+左右padding)*2 = (500+40*2)*2 = 1160,可自行调整 */ text-size-adjust: none; -webkit-text-size-adjust: none; } body { margin: 0 !important; padding: 0 !important; font-size: 16px; line-height: 26px; font-family: "Times New Roman", serif; font-weight: normal; font-style: normal; font-variant: normal; text-align: center; background-color: black; color: white; text-indent: 0; white-space: normal; } .section__article_center { display: flex; justify-content: center; align-items: center; flex-direction: column; } .section-article__table { text-align: center; min-width: var(--table-image-width); width: 80%; border: 1px solid white; table-layout: auto; } .section-article__table img { width: var(--table-image-width); max-width: 100%; /* 新增:图片宽度不超过容器宽度,适配小屏 */ } .section-article__table tr { display: flex; flex-direction: row; justify-content: center; /* 去掉原有的flex-wrap: wrap,改为媒体查询统一控制折叠 */ } .section-article__table td { border: 1px solid white; padding: 10px 40px; overflow: hidden; flex-grow: 1; flex-basis: 50%; /* 修改:固定两列各占一半宽度,避免内容影响宽度 */ display: flex; align-self: stretch; align-items: center; flex-direction: column; justify-content: center; } /* 新增:偶数行调整顺序,实现大屏图文交替 */ .section-article__table tr:nth-child(even) td:first-child { order: 2; } .section-article__table tr:nth-child(even) td:last-child { order: 1; } /* 新增:媒体查询,小于阈值时所有行统一折叠为单列 */ @media (max-width: 1160px) { .section-article__table { min-width: 100%; /* 去掉最小宽度限制,适配小屏 */ width: 95%; } .section-article__table tr { flex-direction: column; } .section-article__table td { order: initial !important; /* 重置顺序,所有行统一图片在上、文字在下 */ flex-basis: auto; } }
效果说明
- 大屏宽度大于1160px时,奇数行图片在左、文字在右,偶数行文字在左、图片在右,符合你原有的交替排列需求
- 宽度小于1160px时,所有行同步折叠为单列,且所有行都是图片在上、文字在下,不会出现顺序错乱问题
- 你可以根据需求调整
--fold-threshold变量的数值,自定义触发折叠的屏幕宽度
内容的提问来源于stack exchange,提问作者Indefinite Person
相关产品推荐
相关产品推荐

