如何居中浮动元素? [英] How do I center floated elements?
问题描述
我正在执行分页,它需要居中.问题在于链接需要显示为块,因此它们需要浮动.但是然后,text-align: center;
不适用于它们.我可以通过给左边的wrapper div填充来实现,但是每个页面都有不同数量的页面,所以这是行不通的.这是我的代码:
I'm implementing pagination, and it needs to be centered. The problem is that the links need to be displayed as block, so they need to be floated. But then, text-align: center;
doesn't work on them. I could achieve it by giving the wrapper div padding of left, but every page will have a different number of pages, so that wouldn't work. Here's my code:
.pagination {
text-align: center;
}
.pagination a {
display: block;
width: 30px;
height: 30px;
float: left;
margin-left: 3px;
background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
width: 90px;
background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
width: 60px;
background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
<a class='first' href='#'>First</a>
<a href='#'>1</a>
<a href='#'>2</a>
<a href='#'>3</a>
<a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->
要弄清主意,我想要什么:
To get the idea, what I want:
推荐答案
删除float
并使用inline-block
可能会解决您的问题:
Removing float
s, and using inline-block
may fix your problems:
.pagination a {
- display: block;
+ display: inline-block;
width: 30px;
height: 30px;
- float: left;
margin-left: 3px;
background: url(/images/structure/pagination-button.png);
}
(删除以-
开头的行,并添加以+
开头的行.)
(remove the lines starting with -
and add the lines starting with +
.)
.pagination {
text-align: center;
}
.pagination a {
+ display: inline-block;
width: 30px;
height: 30px;
margin-left: 3px;
background: url(/images/structure/pagination-button.png);
}
.pagination a.last {
width: 90px;
background: url(/images/structure/pagination-button-last.png);
}
.pagination a.first {
width: 60px;
background: url(/images/structure/pagination-button-first.png);
}
<div class='pagination'>
<a class='first' href='#'>First</a>
<a href='#'>1</a>
<a href='#'>2</a>
<a href='#'>3</a>
<a class='last' href='#'>Last</a>
</div>
<!-- end: .pagination -->
inline-block
可以跨浏览器运行,即使在IE6上也可以,只要该元素最初是嵌入式元素即可.
inline-block
works cross-browser, even on IE6 as long as the element is originally an inline element.
从 quirksmode 引用:
内联块被内联放置(即与相邻内容位于同一行),但是它的行为就像一个块.
An inline block is placed inline (ie. on the same line as adjacent content), but it behaves as a block.
这通常可以有效地替换浮点数:
this often can effectively replace floats:
此值的真正用途是当您要向内联元素赋予宽度时.在某些情况下,某些浏览器不允许在真正的内联元素上使用宽度,但是如果您切换到显示:inline-block,则可以设置宽度." ( http://www.quirksmode.org/css/display.html#inlineblock ).>
根据 W3C规范:
[inline-block]使元素生成一个内联级别的块容器.内联块的内部被格式化为块框,元素本身被格式化为原子内联级别框.
[inline-block] causes an element to generate an inline-level block container. The inside of an inline-block is formatted as a block box, and the element itself is formatted as an atomic inline-level box.
这篇关于如何居中浮动元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!