两个元素定位,要求子元素垂直居中

时间:2022-05-06
本文章向大家介绍两个元素定位,要求子元素垂直居中,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
<!DOCTYPE html>
<html>
 <hed>
 <meta charset="utf-8">
 <title></title>
 <style>
   /*普通定位*/
 #div1{
 width: 598px;
 height: 498px;
 margin: 20px auto;
 background: gray;
 padding: 1px;
 }
 #inner_div1{
 width: 200px;
 height: 150px;
 background: ghostwhite;
 margin-left: 200px;
 margin-top: 150px;
 }
 /*绝对定位:对于不确定宽高的元素,也可以用这个方法,但是得借助js脚本*/
 #div2{
 position: relative;
 width: 598px;
 height: 498px;
 margin: 20px auto;
 background: gray; 
 }
 #inner_div2{
 position: absolute;
 width: 200px;
 height: 150px;
 background: ghostwhite;
 left: 200px;
 top: 150px;
 }
     /*流式定位,这种布局很方便,但是兼容性不好,对于高度不确定的父元素,子元素都适用*/
 #div3{  
 width: 598px;
 height: 498px;
 margin: 20px auto;
 background: gray; 
 display: flex;
 justify-content:center;
 align-items:center;
 }
 #inner_div3{
 width: 200px;
 height: 150px;
 background: ghostwhite;
 }
 /*每一种css定位方式,都可以用js动态控制*/
 </style>
 </hed>
 <body>
 <div id="parent_node">
 <div id="child_node">有两个元素,分别为父元素子元素,高度与宽度都确定,要垂直居中对齐:第一种实现js,js又可以分为两种方式
 第一种是普通定位,第二种是绝对定位
 </div>
 </div>
 <div id="div1">
 <div id="inner_div1">有两个元素,分别为父元素子元素,高度与宽度都确定,要垂直居中对齐:第2种实现css,
 css又可以分为两种方式
 第一种是普通定位,第二种是绝对定位</div>
 </div>
 <div id="div2">
 <div id="inner_div2">有两个元素,分别为父元素子元素,高度与宽度都确定,要垂直居中对齐:第2种实现css,
 css又可以分为两种方式
 第一种是普通定位,第二种是绝对定位
 </div>
 </div>
 <div id="div3">
 <div id="inner_div3">有两个元素,分别为父元素子元素,高度与宽度都确定,要垂直居中对齐:第2种实现css,
 css又可以分为两种方式
 第一种是普通定位,第二种是绝对定位,第三种流式布局
 </div>
 </div>
 </body>
</html>
<script>
var prent_node=document.getElementById("parent_node");
var child_node=document.getElementById("child_node");
 parent_node.style.width="800px";
 parent_node.style.height="200px";
 parent_node.style.background="red";
 parent_node.style.margin="0 auto";
 parent_node.style.position="relative";
 child_node.style.width="400px";
 child_node.style.height="100px";
 child_node.style.background="green";
 child_node.style.position="absolute";
//由于要居中,所以到父的距离,就是父的高-的高,再除以2
 child_node.style.top=(parent_node.offsetHeight-child_node.offsetHeight)/2+"px";
 child_node.style.left=(parent_node.offsetWidth-child_node.offsetWidth)/2+"px";
</script>