居中< div>元件 [英] Centering inside a <div> element
问题描述
我知道这个问题已经被问过一百万次了,我已经在我创建的其他网站中使用了所有这些解决方案,并且他们工作得很好。
然而,在我最近的情况下,通常的答案并不适合我。
这是需要其他元素居中的类(即列表,表):
.container {
位置:相对;
宽度:80%;
身高:90%;
背景颜色:#282828;
box-shadow:inset -6px -6px 6px -2px#1d1d1d;
颜色:#FFF;
border-radius:0 10px 0 0;
float:left;
}
我添加了位置:relative
,因为我把另一个孩子< div>
置于 .container
中,其位置设置为绝对
。我实际上设法把事情集中起来,但那不是我需要的那种中心。当我在 .container
内添加了一个类似于表格的div结构时,它直接返回到左侧 - 不知道为什么。
JSFiddle: http://jsfiddle.net/J3jm7/3/
元素
要在一个内联元素中居中,只需在容器上使用 text-align:center
。 b
$ b
.container {
text-align:center
}
居中块级元素
使用 margin:auto
如
.container表{
margin:auto;
}
居中列表
列表有点儿由于 li {display:list-item; }
。以< ul>
为中心,您需要将其更改为 inline-block
元素,并将其居中
.container {
text-align:center
}
.container ul {
padding:0;
display:inline-block;
}
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/
Centering an inline element
To center an inline element just use text-align:center
on the container.
.container {
text-align:center
}
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;
}
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;
}
这篇关于居中< div>元件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!