本章节介绍一下如何实现未知宽高的元素在指定元素下实现垂直水平居中效果,下面就以span元素为例子,介绍一下如何实现span元素在div中实现水平垂直居中效果,代码如下:
   [ 其他 ] 运行代码    下载代码
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="https://www.51qianduan.com/" />
<title>51前端</title>
<style type="text/css">
#box{
  width:200px;
  height:150px;
  background:blue;
  position:relative;
}
#antzone{
  background:green;
}
</style>
<script type="text/javascript">
window.onload=function(){
  var obox=document.getElementById("box");
  var oantzone=document.getElementById("antzone");
  var w=oantzone.offsetWidth;
  var h=oantzone.offsetHeight;
  oantzone.style.position="absolute";
  oantzone.style.left="50%";
  oantzone.style.top="50%";
  
  oantzone.style.marginLeft=-(w/2)+"px";
  oantzone.style.marginTop=-(h/2)+"px";
}
</script>
</head>
<body>
<div id="box">
  <spanj id="antzone">51前端</span>
</div>
</body>
</html>

代码描述:js元素 垂直水平居中。js元素垂直水平居中代码实例



114 151



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到