我需要将此#wrapper <div>放在页面上没有侧栏的区域中。通过这些选项,它位于整个<body>的中心,并在侧边栏的后面。



#wrapper /* Centers #posts <div>, but at the same time it makes #posts <div> go behind the sidebar, which I don't want to. */ {
    width: 800px;
}
#posts {
    width: 800px;
    float: left; /* Is needed for the Masonry script. */
}
.entry /* Sets options for each post in two columns in #posts <div>. */ {
    width: 400px; /* Musthave option too. */
}
#sidebar {
    position: fixed;
    top: 0px;
    right: 0px;
    width: 250px;
    height: 100%;
    display: table; /* Is needed for centering stuff inside of the sidebar. */
}


<body>
    <div id='wrapper'> <!-- This one is supposed to be centered in the sidebar-free area on the page. -->
        <div id='posts'>
            <!-- Here are all of the posts. -->
                <div class='entry'>
                </div>
        </div>
    </div>
    <div id='sidebar'>
    </div>
</body>




现在看起来像什么:

javascript - 在没有侧边栏的区域中将&lt;div&gt;居中-LMLPHP

我看起来像什么:

javascript - 在没有侧边栏的区域中将&lt;div&gt;居中-LMLPHP

最佳答案

您可以在主体上添加一些填充以补偿侧边栏的宽度。如果您添加与侧边栏宽度相同的填充量,整个主体将被推向左侧。请查看摘要。

如果不需要支持,也可以使用flex-box实现此目的



/* New =================================================================== */

body {
    /* Push content of the body to the left. Use same amount as the sidebar width */
    padding-right: 250px;
    /* Remove default margin */
    margin: 0;
}

#wrapper {
    /* Centers the wrapper */
    margin: 0 auto;
}

/* Old =================================================================== */

#wrapper /* Centers #posts <div>, but at the same time it makes #posts <div> go behind the sidebar, which I don't want to. */ {
    width: 800px;
}
#posts {
    width: 800px;
    float: left; /* Is needed for the Masonry script. */
}
.entry /* Sets options for each post in two columns in #posts <div>. */ {
    width: 400px; /* Musthave option too. */
}
#sidebar {
    position: fixed;
    top: 0px;
    right: 0px;
    width: 250px;
    height: 100%;
    display: table; /* Is needed for centering stuff inside of the sidebar. */
}

/* Demo ============================================================= */

#wrapper {
    /* So you can see it in the demo */
    height: 80px;
    background: red;
}

#sidebar {
    /* So you can see it in the demo */
    height: 80px;
    background: blue;
}

<body>
    <div id='wrapper'> <!-- This one is supposed to be centered in the sidebar-free area on the page. -->
        <div id='posts'>
            <!-- Here are all of the posts. -->
                <div class='entry'>
                </div>
        </div>
    </div>
    <div id='sidebar'>
    </div>
</body>

08-04 11:41