我使用了两个div,一个父级和一个子级。父元素的宽度为100%,其内容与文本居中对齐。
子div的宽度应该为零(或接近它的值),并使用其内容自动扩展其宽度,同时仍在父div中居中。示例:
+------------ PARENT DIV ------------+
| |
| ..some content.. |
| |
| +--CHILD DIV--+ |
| |Inside child | |
| +-------------+ |
| |
+------------------------------------+
+------------ PARENT DIV ------------+
| |
| ..some content.. |
| |
| +------ CHILD DIV ------+ |
| |Inside child with more | |
| +-----------------------+ |
| |
+------------------------------------+如果我给子div设置一个固定的宽度,我可以正确地将它居中:
.parent {
width: 100%;
}
.child {
width: 100px;
margin-left: auto;
margin-right: auto;
}但这不是我需要的,我需要孩子div根据它的内容扩展它的宽度。所以我尝试使用float和nowrap
.parent {
width: 100%;
}
.child {
float: left;
white-space: nowrap;
margin-left: auto;
margin-right: auto;
}这对子对象本身有效,但它不再作为父对象的内容居中。
我可以用Javascript解决这个问题,但我真的不喜欢。
我一直在寻找类似的问题,但我没有找到一个确切地回答这种情况的问题。
有没有人能帮我一把?
提前感谢您的评论。
弗朗西斯科
发布于 2013-04-25 17:01:28
您可以使用display: inline-block; (<p>或另一个<div>)
.parent {
width: 100%;
text-align: center;
border: 1px solid #000;
}
.child {
display: inline-block;
border: 1px solid #f00;
}http://jsfiddle.net/4kpsK/
(单击红色边框div可添加更多内容并查看效果中的解决方案。)
发布于 2013-04-25 16:53:24
你必须让你的孩子使用inline:
.parent {
width: 100%;
text-align: center;
}
.child {
display: inline;
}点击这里查看小提琴:http://jsfiddle.net/4wXTd/1/
发布于 2013-04-25 16:55:45
我认为你可以使用max-width和display:inline来代替width。但这也有缺点:在IE中不能正确解释max-width (我认为至少小于9),但在Webkit/Moz/Opera浏览器中应该是安全的。
https://stackoverflow.com/questions/16210336
复制相似问题