You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在max-width:480px媒体尺寸下使表格caption居中?

解决表格Caption在小屏幕下无法居中的问题

你当前的媒体查询代码里虽然写了text-align: center,但Caption还是靠左,核心原因是小屏幕下表单宽度收缩后,Caption默认和表格宽度一致,导致视觉上看起来没有居中。只需要给小屏幕下的Caption添加width: 100%;,让它占满父容器宽度,就能让居中效果正常显示。

修改后的完整CSS代码如下:

caption {
   font-family: "Rock Salt", cursive;
   padding: 20px;
   font-style: italic;
   caption-side: top;
   color: #666;
   text-align: center;
   letter-spacing: 1px;
}

@media only screen and (max-width: 480px) {
  caption {
    caption-side: top;
    text-align: center;
    letter-spacing: 1px;
    width: 100%; /* 新增这一行,确保Caption占满父容器宽度 */
  }
}

HTML部分无需修改,保持原样即可:

<section id="right"> 
        <table> 
           <caption>Books everyone will enjoy!</caption> 
           <thead> 
              <th colspan="4">Recommended childrens books!</th> 
              <th colspan="2" style="display: none">Recommended childrens books!</th> 
              <tr> 
                 <th colspan="1">Front of the book</th> 
                 <th colspan="1">Title of the book</th> 
                 <th colspan="1">Authors</th> 
                 <th colspan="1">Book Summary</th> 
             </tr> 
           </thead>
</section>

补充说明:width: 100%;会让Caption继承它的父容器(这里是section#right)的宽度,此时text-align: center就会让文字相对于整个父容器居中,而不是只相对于收缩后的表格宽度,这样就能解决小屏幕下Caption靠左的问题。

内容的提问来源于stack exchange,提问作者Michael Swartz Jr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:45:36