调整宽度后如何居中React Flowbite Modal?
解决Flowbite React Modal自定义宽度后不居中的问题
要实现修改宽度同时保持居中,只需要通过添加Tailwind类调整布局即可,核心是确保Modal内容的父容器具备居中能力,这里提供两种简单可行的方案:
方案一:给内容块外层套居中容器
在你当前的内容div(id="A")外面加一层div,添加flex justify-center w-full类,让外层容器占满Modal可用宽度,并通过flex布局让内部内容块居中,之后直接给内容块设置宽度类(比如w-3/4)即可:
<Modal dismissible className="bg-neutral-950/70 backdrop-blur-sm" id="my-modal" show={showMyModal} tabIndex={-1} theme={{ content: { base: 'bg-transparent', inner: 'bg-transparent', }, }} onClose={() => setShowMyModal(false)} onFocus={handleOnFocus} > {/* 新增外层居中容器 */} <div className="flex justify-center w-full"> <div id="A" className="relative p-6 w-3/4 max-h-full bg-neutral-950 border border-neutral-700 rounded-lg shadow"> <div className="mb-6"> <h3 className="text-xl font-semibold text-neutral-100"> Some Header </h3> </div> <div className="mb-6"> <p className="text-sm text-neutral-100"> Some extended block of paragraph text. </p> </div> </div> </div> </Modal>
方案二:修复Modal主题的居中样式
你之前在theme里覆盖了content的base样式,移除了Flowbite默认的flex居中布局类,只需要把这些类加回去,就能让内容自动居中,再给内容块设置宽度类即可:
<Modal dismissible className="bg-neutral-950/70 backdrop-blur-sm" id="my-modal" show={showMyModal} tabIndex={-1} theme={{ content: { // 添加flex布局类恢复居中能力 base: 'bg-transparent flex justify-center items-center', inner: 'bg-transparent', }, }} onClose={() => setShowMyModal(false)} onFocus={handleOnFocus} > <div id="A" className="relative p-6 w-3/4 max-h-full bg-neutral-950 border border-neutral-700 rounded-lg shadow"> <div className="mb-6"> <h3 className="text-xl font-semibold text-neutral-100"> Some Header </h3> </div> <div className="mb-6"> <p className="text-sm text-neutral-100"> Some extended block of paragraph text. </p> </div> </div> </Modal>
补充说明
如果需要适配不同屏幕尺寸,可以结合Tailwind响应式类,比如md:w-3/4 w-full,在移动端自动占满宽度,大屏下保持自定义宽度并居中。
内容的提问来源于stack exchange,提问作者superswellsam
相关产品推荐
相关产品推荐

