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

使用Bootstrap实现两个div垂直居中并分别左右对齐

解决方案

要实现「两个元素分别对齐屏幕左右、整体垂直居中」的效果,你需要调整Bootstrap布局类并确保父容器占满视口高度,修改后的完整代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>
        html, body {
            height: 100%;
            margin: 0;
        }
    </style>
    <title>Document</title>
</head>
<body>
    <div class="container min-vh-100 d-flex align-items-center">
        <div class="row w-100 justify-content-between">
            <div>Hello</div>
            <div>World</div>
        </div>
    </div>
    <script src="script.js" defer></script>
</body>
</html>

核心调整点:

  • 给html和body设置height: 100%,让页面根元素占据整个视口高度,为垂直居中提供基础
  • 容器container添加min-vh-100(确保容器高度至少等于视口高度)和d-flex align-items-center,实现内部元素的垂直居中
  • 行row添加w-100(让行占满容器宽度)和justify-content-between,使两个子元素分别靠向行的左右两端
  • 移除原代码中多余的col和align-self-*类,避免这些类干扰布局逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:55:25