如何在ASP.NET Web Form中垂直居中Bootstrap 5 Toast组件?
Bootstrap Toast 垂直居中解决方案
要让Bootstrap Toast在页面垂直居中,只需调整Toast的父容器样式,结合Bootstrap内置的布局类即可实现,具体修改如下:
修改HTML结构
将Toast的外层容器(带有aria-live属性的div)的class替换为以下组合,利用弹性布局实现居中效果:
<asp:Content ID="ctMain" ContentPlaceHolderID="cpMain" runat="server"> <!-- 调整后的Toast容器,实现垂直水平居中 --> <div aria-live="polite" aria-atomic="true" class="d-flex align-items-center justify-content-center vh-100 position-fixed top-0 start-0 w-100"> <div class="toast text-white bg-danger border-0" role="alert" aria-live="assertive" aria-atomic="true" id="toastFail" data-bs-delay="2000" data-bs-autohide="true"> <div class="toast-header"><strong class="mr-auto">Toast Title</strong></div> <div class="toast-body"><span id="spnErr" /></div> </div> </div> <section class="vh-50"> <!-- rest of page content --> </section> </asp:Content>
样式说明
d-flex:将容器设为弹性布局,支持后续居中类的生效align-items-center:让容器内的元素垂直居中justify-content-center:让容器内的元素水平居中vh-100:容器高度占满整个视口高度position-fixed top-0 start-0 w-100:固定容器在视口范围内,避免随页面滚动偏移,同时宽度占满视口
可选优化:提升层级避免遮挡
如果Toast被页面其他元素遮挡,可添加自定义CSS提升其层级:
.toast-container { z-index: 9999; }
给外层容器加上toast-container类即可:
<div aria-live="polite" aria-atomic="true" class="toast-container d-flex align-items-center justify-content-center vh-100 position-fixed top-0 start-0 w-100">
JavaScript调用不变
依旧使用原代码触发Toast显示:
$('#toastFail').toast('show');
内容的提问来源于stack exchange,提问作者TC_Guy
相关产品推荐
相关产品推荐

