[英]center align a div with inline-block display
aligning a div that has width is very simple just setting left and right margin to auto will do the trick: 对齐具有宽度的div非常简单,只需将左右边距设置为auto即可:
<div style="margin:0px auto;">
but in most cases as the content is dynamic, I can't set a width do the div, using the inline-block has the desired result for div's width but the center aligning doesn't work. 但在大多数情况下,由于内容是动态的,我无法设置div的宽度,使用内联块具有div宽度的所需结果,但中心对齐不起作用。 anybody have any Idea how to center a div that its width is defined by its content width? 任何人有任何想法如何居中一个div宽度由其内容宽度定义?
by the way, I want to know if it is possible to do such thing with css, not with jQuery or javascript. 顺便说一句,我想知道是否可以用css做这样的事情,而不是用jQuery或javascript。
<div style="text-align: center;">
<div style="display: inline-block; background: yellow">Hello World</div>
</div>
You can shrink wrap the contents with the varying width. 您可以使用不同宽度收缩包装内容。 You need two containing elements to do this, like so: 你需要两个包含元素才能做到这一点,如下所示:
.outer-wrapper {
float: right;
position: relative;
left: -50%;
}
.inner-wrapper {
position: relative;
left: 50%;
}
http://jsfiddle.net/ExplosionPIlls/te4es/ http://jsfiddle.net/ExplosionPIlls/te4es/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.