Centering inside a <div> element

99封情书 提交于 2019-12-24 19:27:25

问题


I know this question has been asked a million times and I've already used all those solutions in other websites I created and they worked just fine.

However, in my latest situation, the usual answers are not working for me.

This is the class that needs to have other elements centered inside it (ie. lists, tables):

.container {
    position: relative;
    width: 80%;
    height: 90%;
    background-color: #282828;
    box-shadow: inset -6px -6px 6px -2px #1d1d1d;
    color: #FFF;
    border-radius: 0 10px 0 0;
    float: left;
}

I added the position: relative because I put another child <div> inside .container which had its position set to absolute. I actually managed to center things, but that's not the kind of center I need. When I added a table-like div structure inside .container it went straight back to the left - no idea why.

I would appreciate some help.

JSFiddle: http://jsfiddle.net/J3jm7/3/


回答1:


Centering an inline element

To center an inline element just use text-align:center on the container.

.container {
    text-align:center
}

Demo

Centering a block-level element

Use margin:auto to center a block-level element such as a table within its container.

.container table {
    margin:auto;
}

Demo

Centering a list

Lists are a bit of a special case because of li { display: list-item; }. To center a <ul> you will need to change it to an inline-block element and center it on the container.

.container {
    text-align:center
}

.container ul {
    padding:0;
    display:inline-block;
}

Demo




回答2:


You have to set the left and right margins of the element inside of your container. Here's an example, slightly modifying your code so you can see the centering happening on the table element:

<head>
    <style>
        .container {
            position: relative;
            width: 100%;
            height: 800px;
            background-color: #282828;
            box-shadow: inset -6px -6px 6px -2px #1d1d1d;
            color: #FFF;
            border-radius: 0 10px 0 0;
            float: left;
            border:1px solid black;
        }
            .container table {
                width:25%;
                height: 25%;
                margin-left:auto;
                margin-right:auto;
                border:5px solid blue;
            }
    </style>
</head>
    <body>
        <div class="container">
            <table></table>
        </div>
    </body>
</html>


来源:https://stackoverflow.com/questions/19599104/centering-inside-a-div-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!