如何放置 css div 容器 "text-align: center ;"

how to place css div container "text-align: center ;"

在我的 css 中,我有以下内容:

style.css

* {
    margin: 0;
    padding: 0;
}

body {
    width: 100%;
    font-family: 'Cabin', sans-serif;
}

/*.clear {
    clear: both;
}*/

.clear:after {
    display: block;
    clear: both;
    visibility: hidden;
    content: "";
    height: 0;
}

/* HEADER BLOCK */

.header-background {
   
    padding-top: 50px;
}

.header-background > div:first-child {
    width: 100%;
    background: #232323;
}

.header {
    background: #232323;
    color: #B2B2B2;
    width: 80%;
    margin: auto;
}

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

.header a:active {
    color: #19A3A3;
}

#nav {
    position: relative;
    display: block;
    height: 55px;
    line-height: 55px;
    width: 100%;
    max-width: none;
    margin: 0;
    background: #333;

    z-index: 1;
    border-bottom: 1px solid #666;
    font-weight: 600;
    font-family: helvetica, arial, sans-serif;
    font-size: 14px;
}

#nav, #nav * {
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

.nav-item {
    color: #fff;
    text-transform: uppercase;
    text-decoration: none;
}


/* Desktop */

#desktop-nav .nav-item {
    display: block;
    padding: 0 20px;
    float: right;
  
    -webkit-transition: color 200ms linear;
    -moz-transition: color 200ms linear;
    -ms-transition: color 200ms linear;
    -o-transition: color 200ms linear;
    transition: color 200ms linear;
}

#desktop-nav .nav-item:hover, #desktop-nav .nav-item:active {
    opacity: 0.7;
}

我有以下 html:

<body>
    <div class="header-background">
        <!-- <div> -->
         <div id="nav">
             <nav id="desktop-nav">
                <a class="nav-item" href="#1">Github</a>
                <a class="nav-item" href="#2">About</a>
                <a class="nav-item" href="#3">Community</a>
                <a class="nav-item" href="#4">Docs</a>
             </nav>
         </div>    
    </div>
</body>

现在我看到的是:--

但我想要这样的视图:--

菜单应该在中间。我使用了 text-align: center; 但它没有执行。我做错了什么?

在 CSS class

中使用以下 CSS 样式

保证金:0 自动;

目前 #desktop-nav 居中,但它的宽度为 100%,因此您需要将其收缩包装,使其成为 inline-block

然后 text-align:center 在 #nav` 上将其居中。

  #nav {
        text-align: center;
    }

 #desktop-nav {
     display: inline-block;
 }

JSfiddle Demo

改变这个

#nav {
    margin: 0 auto;   //added this
    width: 400px;     //added this
    position: relative;
    display: block;
    height: 55px;
    line-height: 55px;
    max-width: none;
    background: #333;
    z-index: 1;
    border-bottom: 1px solid #666;
    font-weight: 600;
    font-family: helvetica, arial, sans-serif;
    font-size: 14px;
}

Fiddle: https://jsfiddle.net/fuehunfz/