欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
  单行的行内元素
 
  只需要设置单行行内元素的"行高等于盒子的高"即可;
 
  
 
  <style>
 
  #father{
 
  width:500px;
 
  height:300px;
 
  background-color:skyblue;
 
  }
 
  #son{
 
  background-color:green;
 
  height:300px;
 
  }
 
  </style>
 
  <divid="father">
 
  <spanid="son">我是单行的行内元素</span>
 
  </div>
 
  效果:
 
  1556519521438598.jpg
 
  多行的行内元素
 
  使用给父元素设置display:table-cell;和vertical-align:middle;即可;
 
  
 
  <style>
 
  #father{
 
  width:500px;
 
  height:300px;
 
  background-color:skyblue;
 
  display:table-cell;
 
  vertical-align:middle;
 
  }
 
  #son{
 
  background-color:green;
 
  }
 
  </style>
 
  <divid="father">
 
  <spanid="son">我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素</span>
 
  </div>
 
  效果:
 
  1556519558892168.jpg
 
  块级元素
 
  方案一:使用定位
 
  首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的top:50%,即让子元素的左上角垂直居中;
 
  定高度:设置绝对子元素的margin-top:-元素高度的一半px;或者设置transform:translateY(-50%);
 
  
 
  <style>
 
  #father{
 
  width:500px;
 
  height:300px;
 
  background-color:skyblue;
 
  position:relative;
 
  }
 
  #son{
 
  height:100px;
 
  background-color:green;
 
  position:absolute;
 
  top:50%;
 
  margin-top:-50px;
 
  }
 
  </style>
 
  <divid="father">
 
  <divid="son">我是块级元素</div>
 
  </div>
 
  不定高度:利用css3新增属性transform:translateY(-50%);
 
  
 
  <style>
 
  #father{
 
  width:500px;
 
  height:300px;
 
  background-color:skyblue;
 
  position:relative;
 
  }
 
  #son{
 
  width:100px;
 
  background-color:green;
 
  position:absolute;
 
  left:50%;
 
  transform:translateY(-50%);
 
  }
 
  </style>
 
  <divid="father">
 
  <divid="son">我是块级元素</div>
 
  </div>
 
  效果:
 
  1556519576485117.jpg
 
  方案二:使用flexbox布局实现(高度定不定都可以)
 
  使用flexbox布局,只需要给待处理的块状元素的父元素添加属性display:flex;align-items:center;
 
  
 
  <style>
 
  #father{
 
  width:500px;
 
  height:300px;
 
  background-color:skyblue;
 
  display:flex;
 
  align-items:center;
 
  }
 
  #son{
 
  width:100px;
 
  height:100px;
 
  background-color:green;
 
  }
 
  </style>
 
  <divid="father">
 
  <divid="son">我是块级元素</div>
 
  </div>





本文转载自中文网
 

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/jiqiao/j54094.shtml