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

如何使用Bootstrap将SVG或div元素实现水平垂直居中定位

方案1:相对于父容器垂直+水平居中(保留position:absolute定位)

你需要先给父级<section>添加相对定位类,再给绝对定位的容器添加上下偏移和位移类实现居中,修改后代码如下:

<section class="position-relative">
    <div class="container position-absolute top-50 start-50 translate-middle d-flex justify-content-center">
        <div>
            <svg width="200" height="200" viewBox="0 0 600 600" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect width="600" height="600" fill="#C4C4C4"/>
                </svg>  
        </div>
    </div>
</section>
  • position-relative:给父级设置相对定位,让子元素的绝对定位以当前section为参照
  • top-50 start-50:让容器左上角定位到父元素的中心位置
  • translate-middle:通过位移让容器自身中心和父元素中心重合,实现完全居中
  • d-flex justify-content-center:让容器内部的svg元素水平居中,如果你同时需要垂直居中可再加align-items-center,并给容器设置对应高度

方案2:仅水平居中(不需要绝对定位的场景)

如果不需要脱离文档流的绝对定位,直接删掉position-absolute即可,Bootstrap的container类自带mx-auto属性实现水平居中:

<section>
    <div class="container d-flex justify-content-center">
        <div>
            <svg width="200" height="200" viewBox="0 0 600 600" fill="none" xmlns="http://www.w3.org/2000/svg">
                <rect width="600" height="600" fill="#C4C4C4"/>
                </svg>  
        </div>
    </div>
</section>

预期效果示意图:
效果示意图

内容的提问来源于stack exchange,提问作者memento

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:36:03