在 Bootstrap 中居中 4 列 Div

Centering A 4-column Div In Bootstrap

我是 bootstrap 的新手,遇到了麻烦。我已经搜索了一个小时,试图弄清楚如何让我制作的 div(旨在成为 link)显示在页面的中央但是有没有成功。下面是我的 HTML 和 CSS 代码,如果你能帮我弄清楚我做错了什么,我将不胜感激。

HTML

<!DOCTYPE html>

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="categories.css">
        <!-- Latest compiled and minified CSS -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

        <!-- Optional theme -->
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
        <title>Categories</title>
    </head>


    <body>
    <div class="container">

        <div class="row">
            <div class="category col-md-4 col-centered">
                <a class="link" href="http://google.com">TEST</a>
            </div>
        </div>
    </div>

        <!-- Latest compiled and minified JavaScript -->
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    </body>
</html>

CSS

.col-centered{
    float: none;
    margin-left: auto;
    margin-right: auto;
}

.category {
    text-align: center;
    font-size: 5em;
    background: #09719B;
    border-style: solid;
    border-color: black;
}

.category:hover {
    background-color: #064661;
}

.category a{
    color: white;
    display: block;
}

.category:hover a{
    color:white;
    text-decoration: none;
}

使用class:

category col-xs-8 col-xs-offset-2

而不是category col-md-4 col-centered 这将使 div 4/12 即 1/3

如果屏幕尺寸为 <=md.

,父 div 的

这是小提琴 link

将您的 categories.css 添加到 bootstrap css 之后。像下面。这会覆盖 bootstrap 样式。

<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <link rel="stylesheet" type="text/css" href="categories.css">

参考这个https://www.w3.org/TR/html401/present/styles.html#h-14.3.2

另一种使用方式 bootstrap class .col-md-offset-4

您应该使用 .col-md-offset-4 使 .col-md-4 居中。如果您使用默认值 bootstrap,那么您的网格有 12 列。您的 div 有 4 列,因此将它偏移 4 列将使它从第 4 列开始到第 8 列结束,这与居中相同。

强烈建议您阅读 Bootstrap grid, especially offsetting 部分。

这是一个有效的 JSFiddle