求助:Jumbotron子元素无法实现水平与垂直居中
如何让Bootstrap Jumbotron内的子元素水平垂直居中?
我来帮你搞定这个问题!你之前尝试的类要么是Bootstrap旧版本的(比如span8,现在Bootstrap 4+已经改用栅格系统的col-*类),要么是没有配合足够的布局类来实现完整的垂直水平居中效果。
正确的做法是利用Bootstrap的flex布局工具类,直接作用在jumbotron容器上,同时确保容器有足够的高度来体现垂直居中的效果。以下是修改后的完整代码:
<body> <div class="jumbotron d-flex align-items-center justify-content-center min-vh-100"> <div class="text-center"> <h1>Text 1</h1> <p>Text 2</p> <br> <iframe src="https://www.youtube.com/embed/JC82Il2cjqA" width="560" height="315" frameborder="0" allowfullscreen></iframe> <br> <p><a class="btn btn-primary btn-lg" href="#" role="button">Learn more</a></p> </div> </div> </body>
我来给你拆解一下这些类的作用:
d-flex:将jumbotron转换为flex容器,这样内部元素可以使用flex布局的对齐方式align-items-center:让flex容器内的子元素在垂直方向居中justify-content-center:让flex容器内的子元素在水平方向居中min-vh-100:让jumbotron至少占满整个视口的高度(viewport height),这样垂直居中的效果才能直观体现出来,如果没有这个类,jumbotron的高度只会包裹内容,垂直居中就看不出来了text-center:让子容器内的文本、按钮等行内/行内块元素居中对齐,同时iframe作为块级元素也会在flex容器的水平居中作用下自动居中
这样修改后,你的jumbotron内部的所有内容就会完美实现水平和垂直居中啦!
内容的提问来源于stack exchange,提问作者Prometheus
相关产品推荐
相关产品推荐

