Div居中的方法

1.固定高宽(width: 200px;height: 100px;)

position: absolute;
left: 50%;
top: 50%;
width: 200px;
height: 100px;
margin-left: -100px;
margin-top: -50px;
background: red;

2.不固定高宽div垂直居中的方法(利用伪元素)

index.html

<div class="block" style="height: 300px;">
		<div class="centered">
				<h1>居中标题</h1>
				<p>abc</p>
		</div>
</div>

index.css

/* This parent can be any width and height */
.block {
  text-align: center;
}
 
/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}
 
/* The element to be centered, can
   also be of any width and height */ 
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 50%;
}

3.这种方法是比较成熟的不是固定高宽div的垂直居中的方法


    <div class="center"></div>

.center {
  position: fixed;
  top: 50%;
  left: 50%;
  background-color: #000;
  width:50%;
  height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
}

4.运用margin:auto进行垂直居中

转载:liwenjieIT

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值