javascript - CSS:无法让相对定位的 div 中的文本居中对齐?

标签 javascript jquery html css

我的 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/

相关文章:

Javascript:从字符串(包括查询字符串)中提取 URL 并返回数组

javascript - jQuery each 查找 attr 的标签不起作用

javascript - document.getElementById.innerHTML 不工作

c# - MVC - 保留模型结果以用于 ajax 方法而不通过 JSON 传入?

javascript - 如何获取输入的计算列的总和

javascript - 在 Angular-ui-modal 中使用 Angular-ui-bootstrap 日期的奇怪行为

javascript - Ajax json 请求和响应

javascript - 如何在 HTML Canvas 上旋转矩形?

javascript - lodash 可以删除仅包含 null 或 undefined 的数组吗?

Javascript 在鼠标悬停时填充隐藏字段 - 单击之前