CSS实现子元素垂直居中对齐

来源:互联网 发布:奚梦瑶天涯扒皮知乎 编辑:程序博客网 时间:2024/06/03 23:46


题目如下:实现子元素垂直居中对齐

<!DOCTYPE html><html><head><meta charset="utf-8"><title>demo</title><style type="text/css">.parent { }.children{}</style></head><div class="parent">  <div class="children">子元素垂直居中对齐</div></div><body></body></html>  
(1)方法1:利用margin

.parent {  width:250px;  height:250px;  background-color:grey;  border:1px solid #000000;}.children{  width:50px;  height:50px;    background-color:blue;  margin-left:100px;  margin-top:100px;}

(2)方法二:利用css的 position属性,把div2相对于div1的top、left都设置为50%,然后再用margin-top设置为div2的高度的负一半拉回来,用marg-left设置为宽度的负一半拉回来。

  • 父元素相对定位,子元素绝对定位;
  • 将子元素left和right直接设为50%,相对的是父元素;
  • 然后在使用margin-left和margin-top设为子元素的一半的负数。就是将偏离父元素中心的那段拽回来;

.parent {  width:250px;  height:250px;  background-color:grey;  border:1px solid #000000;  position:relative;}.children{  width:50px;  height:50px;    background-color:blue;  position:absolute;  top:50%;  left:50%;    margin-left:-25px;  margin-top:-25px;}

(3)方法3:
  • 父元素相对定位,子元素绝对定位;
  • 绝对定位盒子模型有个特点:left+right+width+padding+margin=包含块的宽度;所以此时可以将left、right(默认值为auto,所以需要重设置)设置为0,而padding已经确定(未设置时默认值为0px),所以剩下的都是margin,但是margin的默认值是0px。所以就将magin设为auto,使得元素自动居中了;
  • 即:left、right、top、bottom为0;margin为auto; 

.parent {  width:250px;  height:250px;  background-color:grey;  border:1px solid #000000;  position:relative;}.children{  width:50px;  height:50px;    background-color:blue;  position:absolute;  margin:auto;    top:0;  right:0;  bottom:0;  left:0;}

(4)方法4

.parent {  width:250px;  height:250px;  background-color:grey;  border:1px solid #000000;    display:table-cell;  vertical-align:middle;}.children{  width:50px;  height:50px;    background-color:blue;    margin:auto;  }


--------------------------------------------------------------------------------------------

2017年9月24日

方法1

.parent {width:200px;height:200px;border:2px solid #000;position:relative;} .child {width:100px;height:100px;margin: auto;position: absolute;  top: 0; left: 0; bottom: 0; right: 0; background-color: red;}

方法2


.parent {width:800px;height:500px;border:2px solid #000;display:table-cell;vertical-align:middle;text-align: center;}.child {width:200px;height:200px;display:inline-block;background-color: red;}


方法3


.parent {width:800px;height:500px;border:2px solid #000;display:flex;justify-content:center;align-items:center;}.child {width:200px;height:200px;background-color: red;}


方法4

.parent {width:800px;height:500px;border:2px solid #000;position:relative;}.child {width:300px;height:200px;margin:auto;position:absolute;left:50%;top:50%;margin-left: -150px;margin-top:-100px;background-color: red;}