我的 TextWrapper
div 中的文本不会居中对齐。 text-align: center
在我没有使用 position: relative
和 : absolute
时有效,但它们对于我的 jQuery 代码是必需的.如何让文本在 div 中居中对齐?
最佳答案
绝对定位消除了 block 元素填充其父元素宽度的默认行为。添加 width: 100%
或 left: 0; right: 0;
到绝对定位的 div。
$(function(){
$("#TextWrapper div:gt(0)").hide();
setInterval(function(){
var current = $('#TextWrapper div:visible');
var next = current.next().length ? current.next() : $('#TextWrapper div:eq(0)');
current.fadeOut(500);
next.fadeIn(500);
}, 1000);
});
.Border {
border: 1px solid black;
display: inline-flex;
height: 110px;
}
#ImgAndText {
text-align: center;
}
.Img {
width: 75px;
height:75px;
}
#TextWrapper {
font-family: Helvetica;
font-size: 13px;
padding: 5px 5px 5px 5px;
position: relative;
text-align: center;
}
#TextWrapper div {
position: absolute;
text-align: center;
left: 0;
right: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="Border">
<div id="ImgAndText">
<img src="#" class="Img">
<div id="TextWrapper">
<div>Text</div>
<div>Other</div>
</div>
</div>
</div>
关于javascript - CSS:无法让相对定位的 div 中的文本居中对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43335127/