如何在Bootstrap中让h1宽度适配文本而非占满父行?
问题
我把标题放进row容器里来控制高度,目前高度设置已经生效,但h1元素占满了整个row的宽度。我想让h1的宽度只适配文本内容,而不是和父级row一样宽,有没有实现方法?
解决方案
方法一:转成行内块元素
h1默认是块级元素,会自动占满父容器宽度。给h1添加Bootstrap的d-inline-block类,将它改为行内块元素,宽度就会自动贴合文本内容。同时给外层row添加justify-content-center类,让标题在row中水平居中:
修改后的核心代码:
<div class="row justify-content-center"> <h1 class="display-4 mt-3 text-secondary text-center border d-inline-block" contenteditable="true" > Survey Name </h1> </div>
方法二:使用内容适配宽度类
Bootstrap提供了w-fit-content类,可直接让元素宽度适配自身内容。再给h1添加mx-auto类实现水平居中,无需修改元素的显示类型:
修改后的核心代码:
<div class="row"> <h1 class="display-4 mt-3 text-secondary text-center border w-fit-content mx-auto" contenteditable="true" > Survey Name </h1> </div>
完整修改后的代码
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Survey Creato</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" integrity="sha384-r4NyP46KrjDleawBgD5tp8Y7UzmLA05oM1iAEQ17CSuDqnUK2+k9luXQOfXJCJ4I" crossorigin="anonymous" /> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.5.0/font/bootstrap-icons.css" /> </head> <body style="background-color: rgb(0, 0, 0)"> <div style="height: 120px"> <div class="w-100 h-50" style="background-color: rgb(255, 255, 255)"> </div> <div class="w-100 h-50 d-inline-block" style="background-color: rgb(134, 188, 37)" ></div> </div> <div class="d-flex justify-content-center mt-5"> <div id="survey" class="container justify-content-center" style="height: 600px; width: 1000px; background-color: white" > <div class="row justify-content-center"> <h1 class="display-4 mt-3 text-secondary text-center border d-inline-block" contenteditable="true" > Survey Name </h1> </div> </div> </div> </body>
内容的提问来源于stack exchange,提问作者Chris Costa
相关产品推荐
相关产品推荐

