欢迎光临
我们一直在努力

HTML中元素居中要注意哪些事项

这篇文章主要讲解了“HTML中元素居中要注意哪些事项”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“HTML中元素居中要注意哪些事项”吧!

  不使用定位

  水平居中:text-align=center;(可继承)

  竖直居中:margin:0auto;(块级元素)

  其他居中:

      1.文字居中:父元素设置高子元素设置高line-height=height(父元素)

  2.图片居中:vertical-aign:middle;<–必须放在图片元素中

  .first{

  width:300px;

  height:100px;

  background-color:black;

  color:white;

  text-align:center;

  margin:0auto;//针对块级元素

  }

  <divclass="first">

  不使用定位(1)

  </div>

  .second{

  width:300px;

  height:100px;

  background-color:green;

  }

  .s_child{

  width:150px;

  line-height:100px;

  }

  <divclass="second">

  <divclass="s_child">

  不使用定位(2)

  </div>

  </div>

  2.定位居中

  a.父元素高度固定

  父元素:相对定位

  子元素:绝对定位

  top:50%(父元素高度的一半)

  left:50%

  margin-top:自己的高度一半;(加负号)

  margin-left:自己宽度的一半;(加负号)

  .dw_one{

  width:600px;

  height:300px;

  position:absolute;

  background:black;

  }

  .dw_one_child{

  background:white;

  position:relative;

  width:50px;

  height:50px;

  top:50%;

  left:50%;

  margin-top:-25px;

  margin-left:-25px;

  }

  <divclass="dw_one">

  <divclass="dw_one_child">

  a

  </div>

  </div>

  b.父元素高度不固定

  .wrapper{

  width:600px;

  height:600px;

  }

  .dw_two{

  width:100%;

  height:100%;

  position:absolute;

  background:black;

  }

  .dw_two_child{

  background:white;

  position:relative;

  top:50%;

  left:50%;

  width:100px;

  height:100px;

  transform:translate(-50%,-50%);

  -moz-transform:translate(-50%,-50%);

  -ms-transform:translate(-50%,-50%);

  -o-transform:translate(-50%,-50%);

  -webkit-transform:translate(-50%,-50%);

  }

  <divclass="wrapper">

  <divclass="dw_two">

  <divclass="dw_two_child">

  a

  </div>

  </div>

  </div>

  3.关于多行文本的居中

  使用display:table;display:table-cell;

  vertical-align:middle;居中

  #outer{

  width:200px;

  height:200px;

  background:#cccccc;

  display:table;

  _position:relative;//"_"为了兼容IE6

  }

  #inner{

  display:table-cell;

  vertical-align:middle;

  _position:absolute;

  _top:50%;

  }

  #content{

  _position:relative;

  _top:-50%;

  }

  <divid="outer">

  <divid="inner">

  <divid="content">

  </div>

  </div>

  </div>

感谢各位的阅读,以上就是“HTML中元素居中要注意哪些事项”的内容了,经过本文的学习后,相信大家对HTML中元素居中要注意哪些事项这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是云搜网,小编将为大家推送更多相关知识点的文章,欢迎关注!

赞(0)
【声明】:本博客不参与任何交易,也非中介,仅记录个人感兴趣的主机测评结果和优惠活动,内容均不作直接、间接、法定、约定的保证。访问本博客请务必遵守有关互联网的相关法律、规定与规则。一旦您访问本博客,即表示您已经知晓并接受了此声明通告。