Bootstrap 5卡片内容无法正确居中,期望内容居中而非右对齐
解决Bootstrap 5卡片内容居中的问题
你只需做两处调整,就能让卡片内所有内容完全居中:
- 给卡片的
card-body添加text-center类,让标题、文本等内容居中对齐 - 给
form-outline添加d-flex flex-column align-items-center类,确保表单标签和输入框也在水平方向居中
修改后的完整代码如下:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bootstrap demo</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> </head> <body> <h1>Hello, world!</h1> <div class="container mt-5 p-5"> <div class="row g-4"> <div class="col-12 col-md-6 col-lg-3"> <div class="card align-items-center bg-light"> <img src="img/oranvour.png" alt="dfg juice" class="card-img-top"> <div class="card-body text-center"> <h5 class="card-title">Juice</h5> <p class="card-text">Price: $199.00</p> <div class="form-outline d-flex flex-column align-items-center"> <label class="form-label" for="typeNumber">amount</label> <input type="number" id="typeNumber" class="form-control" style="max-width: 120px;" /> </div> </div> </div> </div> </div> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </body> </html>
补充说明:
text-center是Bootstrap内置类,直接控制文本、内联元素的水平居中d-flex flex-column align-items-center将表单区域转为垂直flex布局,强制标签和输入框在水平方向居中- 输入框的
max-width: 120px是为了避免输入框过宽,可根据实际需求调整数值或直接移除
内容的提问来源于stack exchange,提问作者John Johnson
相关产品推荐
相关产品推荐

