Html 居中没有宽度的 div 块
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/283961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Centering a div block without the width
提问by Mike M. Lin
I have a problem when I try to center the div block "products" because I don't know in advance the div width. Anybody have a solution?
当我尝试将 div 块“产品”居中时遇到问题,因为我事先不知道 div 宽度。有人有解决方案吗?
Update: The problem I have is I don't know how many products I'll display, I can have 1, 2 or 3 products, I can center them if it was a fixed number as I'd know the width of the parent div, I just don't know how to do it when the content is dynamic.
更新:我遇到的问题是我不知道要展示多少产品,我可以有 1、2 或 3 个产品,如果它是固定数字,我可以将它们居中,因为我知道父级的宽度div,就是不知道内容动态的时候怎么做。
.product_container {
text-align: center;
height: 150px;
}
.products {
height: 140px;
text-align: center;
margin: 0 auto;
clear: ccc both;
}
.price {
margin: 6px 2px;
width: 137px;
color: #666;
font-size: 14pt;
font-style: normal;
border: 1px solid #CCC;
background-color: #EFEFEF;
}
<div class="product_container">
<div class="products" id="products">
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
<div id="product_15">
<img src="/images/ecommerce/card_default.png">
<div class="price">R$ 0,01</div>
</div>
</div>
</div>
回答by Mike M. Lin
Update 27 Feb 2015:My original answer keeps getting voted up, but now I normally use @bobince's approach instead.
2015 年 2 月 27 日更新:我的原始答案不断被投票,但现在我通常使用 @bobince 的方法。
.child { /* This is the item to center... */
display: inline-block;
}
.parent { /* ...and this is its parent container. */
text-align: center;
}
My original post for historical purposes:
我出于历史目的的原始帖子:
You might want to try this approach.
您可能想尝试这种方法。
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
<div class="clear"/>
</div>
Here's the matching style:
这是匹配的样式:
.outer-center {
float: right;
right: 50%;
position: relative;
}
.inner-center {
float: right;
right: -50%;
position: relative;
}
.clear {
clear: both;
}
The idea here is that you contain the content you want to center in two divs, an outer one and an inner one. You float both divs so that their widths automatically shrink to fit your content. Next, you relatively position the outer div with it's right edge in the center of the container. Lastly, you relatively position the inner div the opposite direction by half of its own width (actually the outer div's width, but they are the same). Ultimately that centers the content in whatever container it's in.
这里的想法是您包含要在两个 div 中居中的内容,一个外部的和一个内部的。您浮动两个 div,以便它们的宽度自动缩小以适合您的内容。接下来,您将外部 div 的右边缘相对放置在容器的中心。最后,您将内部 div 相对地定位在其自身宽度的一半的相反方向(实际上是外部 div 的宽度,但它们是相同的)。最终将内容集中在它所在的任何容器中。
You mayneed that empty div at the end if you depend on your "product" content to size the height for the "product_container".
您可能需要一个空div在年底,如果你依靠你的“产品”的内容,规格为“product_container”的高度。
回答by bobince
An element with ‘display: block' (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).
带有 'display: block' 的元素(默认为 div)的宽度由其容器的宽度决定。您不能使块的宽度取决于其内容的宽度(缩小以适应)。
(Except for blocks that are ‘float: left/right' in CSS 2.1, but that's no use for centering.)
(除了 CSS 2.1 中“浮动:左/右”的块,但这对居中没有用。)
You could set the ‘display' property to ‘inline-block' to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.
您可以将 'display' 属性设置为 'inline-block' 以将块转换为可缩小以适应对象,该对象可由其父级的 text-align 属性控制,但浏览器支持参差不齐。如果你想这样做,你可以通过使用 hacks(例如,参见 -moz-inline-stack)来摆脱它。
The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code?—?there's nothing obvious in there that would needa shrink-to-fit block?—?but a list of products could possibly be considered tabular.
另一种方法是桌子。当您的列的宽度确实无法提前知道时,这可能是必要的。我真的无法从示例代码中看出您想要做什么?-?那里没有什么明显的需要收缩以适应块的内容?-?但可以将产品列表视为表格。
[PS. never use ‘pt' for font sizes on the web. ‘px' is more reliable if you really need fixed size text, otherwise relative units like ‘%' are better. And “clear: ccc both”?—?a typo?]
[PS. 永远不要在网络上使用“pt”作为字体大小。如果你真的需要固定大小的文本,'px' 更可靠,否则像 '%' 这样的相对单位更好。和“清楚:同时抄送”?—?打字错误?]
.center{
text-align:center;
}
.center > div{ /* N.B. child combinators don't work in IE6 or less */
display:inline-block;
}
回答by Maxime Rossini
Most browsers support the display: table;
CSS rule. This is a good trick to center a div in a container without adding extra HTML nor applying constraining styles to the container (like text-align: center;
which would center all other inline content in the container), while keeping dynamic width for the contained div:
大多数浏览器都支持display: table;
CSS 规则。这是一个很好的技巧,可以在不添加额外的 HTML 或对容器应用约束样式的情况下将 div 居中在容器中(例如text-align: center;
将容器中的所有其他内联内容居中),同时保持所包含 div 的动态宽度:
HTML:
HTML:
<div class="container">
<div class="centered">This content is centered</div>
</div>
CSS:
CSS:
.centered { display: table; margin: 0 auto; }
.container {
background-color: green;
}
.centered {
display: table;
margin: 0 auto;
background-color: red;
}
<div class="container">
<div class="centered">This content is centered</div>
</div>
Update (2015-03-09):
更新(2015-03-09):
The proper way to do this today is actually to use flexbox rules. Browser support is a little bit more restricted (CSS table supportvs flexbox support) but this method also allows many other things, and is a dedicated CSS rule for this type of behavior:
今天这样做的正确方法实际上是使用 flexbox 规则。浏览器支持受到更多限制(CSS 表支持与flexbox 支持)但此方法还允许许多其他事情,并且是针对此类行为的专用 CSS 规则:
HTML:
HTML:
<div class="container">
<div class="centered">This content is centered</div>
</div>
CSS:
CSS:
.container {
display: flex;
flex-direction: column; /* put this if you want to stack elements vertically */
}
.centered { margin: 0 auto; }
.container {
display: flex;
flex-direction: column; /* put this if you want to stack elements vertically */
background-color: green;
}
.centered {
margin: 0 auto;
background-color: red;
}
<div class="container">
<div class="centered">This content is centered</div>
</div>
回答by Frank Nocke
six ways to skin that cat:
给那只猫剥皮的六种方法:
Button one:anything of type display: block
will assume the full parents width. (unless combined with float
or a display: flex
parent). True. Bad example.
按钮一:任何类型display: block
都将采用完整的父母宽度。(除非与float
或display: flex
父母结合)。真的。不好的例子。
Button 2:going for display: inline-block
will lead to automatic (rather than full) width. You can then center using text-align: center
on the wrapping block. Probably the easiest, and most widely compatible, even with ‘vintage' browsers...
按键2:去为display: inline-block
会导致自动(而不是全部)宽。然后您可以text-align: center
在包装块上使用居中。可能是最简单、最广泛兼容的,即使使用“老式”浏览器...
.wrapTwo
text-align: center;
.two
display: inline-block; // instantly shrinks width
Button 3:No need to put anything on the wrap. So perhaps this is the most elegant solution. Also works vertically. (Browser support for transtlate is good enough (≥IE9)these days...).
按钮 3:无需在包装上放任何东西。所以也许这是最优雅的解决方案。也可以垂直工作。(这些天浏览器对翻译的支持已经足够好(≥IE9)...)。
position: relative;
display: inline-block; // instantly shrinks width
left: 50%;
transform: translateX(-50%);
Btw: Also a great way for vertically centering blocks of unknown height (in connection with absolute positioning).
顺便说一句:也是垂直居中未知高度块的好方法(与绝对定位有关)。
Button 4:Absolute positioning. Just make sure to reserve enough height in the wrapper, since noone else will (neither clearfix nor implicit...)
按钮 4:绝对定位。只要确保在包装器中保留足够的高度,因为没有其他人会(无论是 clearfix 还是隐式......)
.four
position absolute
top 0
left 50%
transform translateX(-50%)
.wrapFour
position relative // otherwise, absolute positioning will be relative to page!
height 50px // ensure height
background lightgreen // just a marker
Button 5:float (which brings also block-level elements to dynamic width) and a relative shift. Although I've neverseen this in the wild. Perhaps there are disadvantages...
按钮 5:浮动(也将块级元素带入动态宽度)和相对位移。虽然我从未在野外见过这种情况。也许有缺点...
.wrapFive
&:after // aka 'clearfix'
content ''
display table
clear both
.five
float left
position relative
left 50%
transform translateX(-50%)
Update:Button 6:And nowadays, you could also use flex-box. Note, that styles apply to the wrapper of the centered object.
更新:按钮 6:现在,您还可以使用 flex-box。请注意,样式适用于居中对象的包装器。
.wrapSix
display: flex
justify-content: center
→ full source code (stylus syntax)
→ 完整源代码(手写笔语法)
回答by JavierIEH
I found a more elegant solution, combining "inline-block" to avoid using float and the hacky clear:both. It still requires nested divs tho, which isnt very semantic but it just works...
我找到了一个更优雅的解决方案,结合“inline-block”以避免使用 float 和 hacky clear:两者。它仍然需要嵌套的 div tho,这不是很语义但它只是工作......
div.outer{
display:inline-block;
position:relative;
left:50%;
}
div.inner{
position:relative;
left:-50%;
}
Hope it helps!
希望能帮助到你!
回答by West1
<div class="outer">
<div class="target">
<div class="filler">
</div>
</div>
</div>
.outer{
width:100%;
height: 100px;
}
.target{
position: absolute;
width: auto;
height: 100px;
left: 50%;
transform: translateX(-50%);
}
.filler{
position:relative;
width:150px;
height:20px;
}
If the target element is absolutely positioned, you can center it by moving it 50% in one direction (left: 50%
) and then transforming it 50% in the opposition direction (transform:translateX(-50%)
). This works without defining the target element's width (or with width:auto
). The parent element's position can be static, absolute, relative, or fixed.
如果目标元素是绝对定位的,您可以通过将其在一个方向 ( left: 50%
) 上移动 50%然后在相反方向 ( transform:translateX(-50%)
)上将其转换 50%来将其居中。这无需定义目标元素的宽度(或使用width:auto
)。父元素的位置可以是静态的、绝对的、相对的或固定的。
回答by zloctb
use css3 flexbox with justify-content:center;
使用带有 justify-content:center 的 css3 flexbox;
<div class="row">
<div class="col" style="background:red;">content1</div>
<div class="col" style="">content2</div>
</div>
.row {
display: flex; /* equal height of the children */
height:100px;
border:1px solid red;
width: 400px;
justify-content:center;
}
回答by Adam Bellaire
By default, div
elements are displayed as block elements, so they have 100% width, making centering them meaningless. As suggested by Arief, you must specify a width
and you can then use auto
when specifying margin
in order to center a div
.
默认情况下,div
元素显示为块元素,因此它们具有 100% 的宽度,使它们居中毫无意义。正如 Arief 所建议的,您必须指定 a width
,然后您可以auto
在指定时使用margin
以将 a 居中div
。
Alternatively, you could also force display: inline
, but then you'd have something that pretty much behaves like a span
instead of a div
, so that doesn't make a lot of sense.
或者,你也可以 force display: inline
,但是你会有一些表现得几乎像 aspan
而不是 a 的东西div
,所以这没有多大意义。
回答by Greg Benner
This will center an element such as an Ordered List, or Unordered List, or any element. Just wrap it with a Div with the class of outerElement and give the inner element the class of innerElement.
这将使元素居中,例如有序列表、无序列表或任何元素。只需用一个带有outerElement 类的Div 将它包装起来,并为内部元素提供innerElement 类。
The outerelement class accounts for IE, old Mozilla, and most newer browsers.
外层元素类用于 IE、旧的 Mozilla 和大多数较新的浏览器。
.outerElement {
display: -moz-inline-stack;
display: inline-block;
vertical-align: middle;
zoom: 1;
position: relative;
left: 50%;
}
.innerElement {
position: relative;
left: -50%;
}
回答by Cicil Thomas
<div class="product_container">
<div class="outer-center">
<div class="product inner-center">
</div>
</div>
<div class="clear"></div>
</div>
.outer-center
{
float: right;
right: 50%;
position: relative;
}
.inner-center
{
float: right;
right: -50%;
position: relative;
}
.clear
{
clear: both;
}
.product_container
{
overflow:hidden;
}
If you dont provide "overflow:hidden" for ".product_container" the "outer-center" div will overlap other nearby contents to the right of it. Any links or buttons to the right of "outer-center" wont work. Try background color for "outer-center" to understand the need of "overflow :hidden"
如果您不为“.product_container”提供“overflow:hidden”,“outer-center”div 将与它右侧的其他附近内容重叠。“外中心”右侧的任何链接或按钮都不起作用。尝试“外中心”的背景颜色以了解“溢出:隐藏”的需要