深入理解CSS居中问题

关于如何在div中居中一个元素,应该是一个前段开发者在前前期常遇到的问题,下面我总结了一下我知道的和大家分享,当然,如果写的不对,还请大家留言指点。

居中一般都是在块元素中居中的

1.元素中 只有文本或者元素是内联元素

	<style type="text/css">
		div{
			width:600px;
			height: 100px;
			background-color: #444444;

			display: table-cell;
			/*表格样式  display: table-cell;*/

			vertical-align: middle;
			/*使当前元素内的内容上下居中   vertical-align: middle;*/

			text-align: center;
			/*文本居中*/

			/*这三句代码可使当前元素内的文本上下左右居中*/
		}

	</style>

	<div>
		元素
	</div>
也可以给元素添加一个p标签


2.里面包裹着一个块元素

	<style type="text/css">
		.box{
			width:600px;
			height: 100px;
			background-color: #444444;

			display: table-cell;
			/*表格样式  display: table-cell;*/

			vertical-align: middle;
			/*使当前元素内的内容上下居中   vertical-align: middle;*/

		}
		.box1{
			width: 20px;
			height: 30px;
			margin: auto;
			background-color: #ccc;
		}

	</style>
</head>
<body>
	<div class="box">
		<div class="box1"></div>
	</div>
</body>

3. 这两句比第一种更方便点,效果和第一个一样        // 固定高的情况下使用这种方法

text-align: center;

line-height: 100px;  

	<style type="text/css">
		div{
			width:600px;
			height: 100px;
			background-color: #444444;
			color:#fff;

			text-align: center;
			line-height: 100px;
			/*文本上下左右居中*/
		}

	</style>
	<div>
		131321
	</div>

4.这一种就比较抽象了。利用的是position定位,

relative 相对定位   相对与当前文档流

	<style type="text/css">
		div{
			width:600px;
			height: 100px;
			background-color: #444444;
		}
		p{
			width: 50px;
			height: 50px;
			position: relative;
			top:50%;
			left: 50%;
			margin-top:-25px; 
			margin-left:-25px; 
			color: #fff;
		}

	</style>
	<div>
		<p>123</p>
	</div>
absolute 绝对定位  当没有父元素relative时 相对与整个HTML定位

fixed 固定定位  

下边的这两个大家就自己试试,毕竟纸上得来终觉浅







猜你喜欢

转载自blog.csdn.net/ListFish/article/details/79709915