Bootstrap卡片内按钮换行问题:如何保持按钮与内容同行?
解决Bootstrap卡片中Delete按钮换行问题
问题根源分析
你的代码存在几个关键问题导致按钮换行:
- 按钮所在的
<span>重复设置了style属性,第二个style="white-space: nowrap;"会被浏览器忽略,无法生效; inline-block元素之间的空白字符(代码中的换行、空格)会被渲染为空格,累加后可能让总宽度超出容器;<form>元素默认带有margin,额外占用了空间。
具体修复方案
方案1:修复代码错误并处理inline-block空白
- 合并按钮span的重复style属性,移除冗余定义;
- 消除inline-block元素间的空白,或通过父元素
font-size: 0隐藏空白,再给子元素恢复字体大小; - 移除表单默认边距。
修复后的代码示例:
<p> <span style="font-size: 0;"> <span style="display: inline-block; width: 100px; font-size: 1rem;"> <strong><?php echo $clientSiteDemandRow['dayOfWeek']; ?></strong> </span><span style="display: inline-block; width: 70px; font-size: 1rem;"> <i class="fa fa-clock"></i> <?php echo $clientSiteDemandRow['shiftStart']; ?> </span><span style="display: inline-block; width: 100px; font-size: 1rem;"> <?php echo $hours; ?> Hours </span><span style="display: inline-block; width: 30px; white-space: nowrap; font-size: 1rem;"> <form action="" method="POST" style="margin: 0;"> <button type="submit" class="btn btn-danger btn-sm" id="deleteSiteDemand" name="deleteSiteDemand" value="<?php echo $clientSiteDemandRow['id']; ?>">Delete</button> </form> </span> </span> </p>
方案2:改用Bootstrap Flex布局(更推荐)
利用Bootstrap内置的flex类替代自定义inline-block,彻底避免空白和宽度计算问题:
<div class="d-flex align-items-center"> <div class="flex-shrink-0" style="width: 100px;"> <strong><?php echo $clientSiteDemandRow['dayOfWeek']; ?></strong> </div> <div class="flex-shrink-0" style="width: 70px;"> <i class="fa fa-clock"></i> <?php echo $clientSiteDemandRow['shiftStart']; ?> </div> <div class="flex-shrink-0" style="width: 100px;"> <?php echo $hours; ?> Hours </div> <div class="flex-shrink-0" style="width: 30px;"> <form action="" method="POST" class="m-0"> <button type="submit" class="btn btn-danger btn-sm" id="deleteSiteDemand" name="deleteSiteDemand" value="<?php echo $clientSiteDemandRow['id']; ?>">Delete</button> </form> </div> </div>
d-flex将容器设为flex布局,子元素默认在同一行;flex-shrink-0防止元素被压缩;m-0消除表单默认边距;align-items-center让元素垂直居中,提升排版美观度。
方案3:使用Bootstrap栅格系统
如果卡片宽度固定,可通过栅格类分配宽度,适配性更强:
<div class="row g-0 align-items-center"> <div class="col-3"> <strong><?php echo $clientSiteDemandRow['dayOfWeek']; ?></strong> </div> <div class="col-2"> <i class="fa fa-clock"></i> <?php echo $clientSiteDemandRow['shiftStart']; ?> </div> <div class="col-3"> <?php echo $hours; ?> Hours </div> <div class="col-4"> <form action="" method="POST" class="m-0"> <button type="submit" class="btn btn-danger btn-sm" id="deleteSiteDemand" name="deleteSiteDemand" value="<?php echo $clientSiteDemandRow['id']; ?>">Delete</button> </form> </div> </div>
g-0移除列之间的间隙;- 根据实际需求调整
col-*数值,确保总宽度为12即可。
内容的提问来源于stack exchange,提问作者David
相关产品推荐
相关产品推荐

