是否有任何方法在主父元素中垂直或水平地居中html元素?
当前回答
我发现在Bootstrap 4中你可以这样做:
中心水平确实是文本中心类
中心垂直,但是使用bootstrap类添加mb-auto mt-auto,使margin-top和margin- bottom设置为auto。
其他回答
更新:虽然这个答案在2013年初可能是正确的,但现在不应该再用了。正确的解决方案使用偏移量,如下所示:
class="mx-auto"
至于其他用户的建议,也有本地引导类可用,如:
class="text-center"
class="pagination-centered"
我发现在Bootstrap 4中你可以这样做:
中心水平确实是文本中心类
中心垂直,但是使用bootstrap类添加mb-auto mt-auto,使margin-top和margin- bottom设置为auto。
对于水平居中,你可以这样做:
.centering{
float:none;
margin:0 auto
}
<div class="span8 centering"></div>
如果你试图在div中居中一个图像,但图像不会居中,这可能描述了你的问题:
JSFiddle演示的问题
<div class="col-sm-4 text-center">
<img class="img-responsive text-center" src="myPic.jpg" />
</div>
img-responsive类向图像标记添加了一个display:block指令,它将停止text-align:center(文本中心类)的工作。
解决方案:
<div class="col-sm-4">
<img class="img-responsive center-block" src="myPic.jpg" />
</div>
解决方案的JSFiddle演示
添加center-block类将覆盖使用img-responsive类放入的display:block指令。如果没有img-responsive类,图像将仅通过添加文本中心类居中
此外,您应该了解flexbox的基础知识以及如何使用它,因为Bootstrap 4现在本机使用它。
这是布拉德·希夫制作的一个优秀的、快节奏的视频教程
这里有一个很棒的小抄
在Bootstrap 4中,你可以使用基于flex的HTML类d-flex、justify-content-center和align-items-center:
<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" rel="stylesheet"/> <div class="d-flex align-items-center"> <button type="submit" class="btn btn-primary">创建</button> < / div >
来源:Bootstrap 4.1