深入理解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 固定定位  

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

 

 

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JwCode

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值