<!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>
本文分享自微信公众号 - 交互设计前端开发与后端程序设计(interaction_Designer),作者:json
原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。
原始发表时间:2015-11-25
本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。
我来说两句