css - 关于水平居中的问题
本文介绍了css - 关于水平居中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>用循环将三个DIV变成红色</title>
<style type="text/css">
div {margin: 0 auto;}
#outer {width: 330px;height: 100px; margin: 10px auto;}
#outer div {float: left;width: 100px;height: 100px;margin: 0 5px;background: black;}
</style>
<script type="text/javascript">
window.onload = function() {
var oDiv = document.getElementById("outer").getElementsByTagName("div");
var oBtn = document.getElementsByTagName("button");
oBtn[0].onclick = function() {
for(var i=0; i<oDiv.length; i++) {
oDiv[i].style.background = "red";
}
}
};
</script>
</head>
<body>
<div><button>点击将DIV变成红色</button></div>
<div id="outer">
<div></div>
<div></div>
<div></div>
</div>
</body>
</html>
1.在有div的情况下,为什么div {margin: 0 auto;}没有效果,后来用了text-align:center可以了
2.在button标签中添加选择器的情况下,无论是margin或者是text-align都不能居中
解决方案
div {margin: 0 auto;}只是让块元素居中,而不是让块元素的子元素也居中。
text-align:center 可以让行内元素的button居中
至于你给button添加margin不成功居中,是因为{margin: 0 auto;}只对块元素起作用,添加text-align:center不起作用,是因为,text-align只对行内块子元素或者内联子元素起作用
这篇关于css - 关于水平居中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文