我正在使用2个div,父母和孩子.父级的宽度为100%,其内容以文本对齐为中心.
子div应该具有零(或接近它)的宽度,并使用其内容自动扩展其宽度,同时仍然在父div中居中.例:
+------------ PARENT DIV ------------+
| |
| ..some content.. |
| |
| +--CHILD DIV--+ |
| |Inside child | |
| +-------------+ |
| |
+------------------------------------+
+------------ PARENT DIV ------------+
| |
| ..some content.. |
| |
| +------ CHILD DIV ------+ |
| |Inside child with more | |
| +-----------------------+ |
| |
+------------------------------------+
Run Code Online (Sandbox Code Playgroud)
如果我为子div添加固定宽度,我可以正确居中:
.parent {
width: 100%;
}
.child {
width: 100px;
margin-left: auto;
margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)
但这不是我需要的,我需要子div根据其内容扩展其宽度.所以我尝试使用float和nowrap:
.parent {
width: 100%;
}
.child {
float: left;
white-space: nowrap;
margin-left: auto;
margin-right: auto;
}
Run Code Online (Sandbox Code Playgroud)
这适用于孩子本身,但它不再以父母的内容为中心.
我可以使用Javascript解决它,但我真的不喜欢.
我一直在寻找类似的问题,但我没有找到一个完全回答这种情况.
有人可以请我点灯吗?
提前感谢您的任何意见.
弗朗西斯科
您可以使用display: inline-block;(在 < IE7 中不支持)但您必须将所有其他内容包含在另一个块级元素中(如 a<p>或 another <div>)
.parent {
width: 100%;
text-align: center;
border: 1px solid #000;
}
.child {
display: inline-block;
border: 1px solid #f00;
}
Run Code Online (Sandbox Code Playgroud)
(单击红色边框的 div 以添加更多内容并查看有效的解决方案。)
| 归档时间: |
|
| 查看次数: |
3190 次 |
| 最近记录: |