温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

css中如何实现上下居中效果

发布时间:2022-02-25 11:36:00 来源:亿速云 阅读:900 作者:小新 栏目:web开发

这篇文章将为大家详细讲解有关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>

css中如何实现上下居中效果css中如何实现上下居中效果


关于“css中如何实现上下居中效果”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

css
AI