美文网首页
div水平垂直居中

div水平垂直居中

作者: 5b5072cc2c5b | 来源:发表于2019-03-18 21:50 被阅读0次
1.position和transform结合

position设置为absolute,top和left分别设置为50%;
再利用translate,translate-x,translate-y分别设置为-50%;

div{
  width: 50%;
  height: 50%;
  position: absolute;
  transform: translate(-50% -50%);
}
2.position和 margin结合

position 设置为absolute,top,left,right,bottom都设置为0,
margin设为auto

div{
  width: 50%;
  height: 50%;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
}
3.flex布局

外层div设置为display:flex,justify-content:center;(水平居中),align-items:center(垂直居中)

<div id="wrapper">
  <div id="content"></div>
</div>
// css
<style>
#wrapper{
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
#content{
  width: 50%;
  heigth: 50%;
  background-color: red;
}
</style>
4.postion:absolute 和vw,vh结合
<div id="wrapper">
  <div id="content"></div>
</div>
<style>
  #wrapper{
  width: 100vw;
  height: 100vh;
  position: relative;
  background-color: blue;
}
#content{
  background-color: yellow;
  width: 50vw;
  height: 50vh;
  position: absolute;
  top: 25vh;
  left: 25vw;
}
</style>
5.table布局

wraper: display: table
content: display: table-cell;text-align: center;vertical-align: center;

 <style>
 #wrapper{
  width: 100%;
  height: 100%;
  display: table;
}
#content{
  width: 50%;
  height: 50%;
  display: table-cell;
  vertical-align: center;
  text-align: center;
}
</style>
6.当div的宽高固定时,可以利用position和负边距

position: absolute,top,left分别为50%;
margin-top,margin-left分别为自身高度,自身宽度的一半的负值

<style>
   div{
      width: 200px;
      height: 200px;
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: -100px;
      margin-bottom: -100px;
    }
</style>

相关文章

  • CSS水平垂直居中总结

    CSS水平居中、垂直居中、水平垂直居中方法总结 文字的水平居中: 单行文字的垂直居中: 让有宽度的div水平居中:...

  • CSS居中大全(带截图)

    文字水平居中 图片水平垂直居中 图片与文字水平垂直居中 代码同上 DIV相对于页面垂直居中并且响应式 视口绝对垂直...

  • [2020-08-10]css3中的常用几种布局

    div的水平垂直居中 flex布局,使用display: flex实现水平垂直居中 grid布局 使用grid布局...

  • 水平垂直居中的实现方法

    小div在大div里面水平垂直居中的实现方法 初学前端时,我们都经常会练习实现关于水平垂直居中。那么你们都会用...

  • html+css,让div水平垂直居中的几种方式

    在web前端开发中经常需要使用到让div进行水平和垂直居中的技术,现在我们就来谈谈如何实现div水平垂直居中(如下...

  • CSS居中

    不用float的多个div的水平居中 div的垂直居中1.display:flex; position:absol...

  • css div垂直居中

    方案一:div绝对定位水平垂直居中【margin:auto实现绝对定位元素的居中】, 方案二:div绝对定位水平垂...

  • 动态设置div css属性

    jQuery实现水平和垂直居中 jQuery实现水平和垂直居中的原理就是通过jQuery设置DIV的CSS,获取D...

  • DIV+CSS实现居中

    垂直居中 height:div的高度line-height:div的行高 并且水平居中 text-align:规定...

  • DIV水平垂直居中

    CSS Code : HTML Code :

网友评论

      本文标题:div水平垂直居中

      本文链接:https://www.haomeiwen.com/subject/xdlimqtx.html