我正在进行动态幻灯片放映。
我正在尝试获取一些动态分配的文本,以便在框内集中和垂直对齐。
到目前为止,我有:
HTML
<body>
<div class="slide">
<span class="content">
<b>Hello. This text needs to be:</b><br><br>
- left-aligned but <br>
- centered in the grey box<br>
- even if it changes<br>
- the center of the white box <br>
should equal center of grey one.
</span>
</div>
</body>
CSS
.slide {
position:relative;
background-color: #ddd;
width: 300px;
height: 300px
}
.content {
position: absolute;
top: 30%;
left: 15%;
background-color: #fff;
}
输出
这不起作用,因为如果文本发生变化,它将不再是中心。任何人有任何想法如何解决这个问题?
答案 0 :(得分:3)
这可以满足您的需求,但依赖于旧版浏览器不支持的display: table-cell
。
.slide {
position:relative;
background-color: #ddd;
display: table-cell;
width: 300px;
height: 300px;
text-align: center;
vertical-align: middle;
}
.content {
background-color: #fff;
display: inline-block;
width: auto;
height: auto;
margin-left: auto;
margin-right: auto;
text-align: left;
}
我认为没有针对旧版浏览器的解决方案不会改变HTML。
编辑:.content
编辑:删除了用于调试的border: 1px solid gray
。
编辑:根据@Shomz建议更改(.content
宽度的新标准不同)。
答案 1 :(得分:1)
如果你不介意滑动高度,这样的东西在任何场合都可以完美地运作:
div.slide {
position:relative;
background-color: #ddd;
text-align: center;
}
div.content {
text-align: left;
position: relative;
display: inline-block;
margin: 10% auto;
background-color: #fff;
}
http://jsbin.com/uyiFiwI/28/edit
但是,如果你的.slide div需要有固定的高度,你可能需要使用JavaScript来正确计算内容div的渲染高度,或使用hacky CSS,它可能在所有浏览器中起作用,也可能不起作用,如@David建议。
答案 2 :(得分:1)
如果您愿意稍微更改标记,使用列表可以帮助您清理一些换行符和间距问题。
将这个与display: table-cell
结合起来,@ David-SkyMesh在他的回答中将会给你一个更易于管理的列表。
<强> HTML 强>
<div class="slide">
<div class="content">
<b>Hello. This text needs to be:</b>
<ul>
<li>left-aligned but</li>
<li>centered in the grey box</li>
<li>even if it changes</li>
<li>the center of the white box this this is really long text not the gray one should equal center of grey one.</li>
</ul>
</div>
</div>
<强> CSS 强>
.slide {
position:relative;
background-color: #ddd;
width: 300px;
height: 300px;
padding: 20px;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.content > ul > li:nth-child(1) {
margin-top: 10px;
}
.content {
display: block;
margin: auto;
background-color: #fff;
text-align: left;
}
.content ul {
margin: 0;
padding: 0;
padding-left: 20px;
}