Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

html - Centering inside a <div> element

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/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...