是否有任何方法在主父元素中垂直或水平地居中html元素?


当前回答

你可以像这样直接写入你的CSS文件:

.content { 位置:绝对的; 上图:50%; 左:50%; 变换:翻译(-50%,-50%); } <div class = "content" > <p>一些文本</p> < / div >

其他回答

在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

我用这个

<style>
    html, body {
        height: 100%;
        margin: 0;
        padding: 0 0;
    }

    .container-fluid {
        height: 100%;
        display: table;
        width: 100%;
        padding-right: 0;
        padding-left: 0;
    }

    .row-fluid {
        height: 100%;
        display: table-cell;
        vertical-align: middle;
        width: 100%;
    }

    .centering {
        float: none;
        margin: 0 auto;
    }
</style>
<body>
    <div class="container-fluid">
        <div class="row-fluid">
            <div class="offset3 span6 centering">
                content here
            </div>
        </div>
    </div>
</body>

我发现在Bootstrap 4中你可以这样做:

中心水平确实是文本中心类

中心垂直,但是使用bootstrap类添加mb-auto mt-auto,使margin-top和margin- bottom设置为auto。

对于水平居中,你可以这样做:

.centering{
float:none;
margin:0 auto
}

 <div class="span8 centering"></div>

Bootstrap 4使用flex属性解决了这个问题。你可以使用这些类:

<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 >

这些类将使您的内容水平和垂直居中。