为了账号安全,请及时绑定邮箱和手机立即绑定

HTML中的居中方法

标签:
Html/CSS

之前我们就总结过很多剧中的方法,但是时间长不用,就会慢慢遗忘,所以我们从头来复习一次,变想边敲代码......

文本居中

height + line-height:两者配合使用,垂直方向居中
text-align:父级的text-align,水平方向居中
注意:text-align:center ;只是将子元素里的内联元素居中
如果不是内联元素就要用到  margin: 0 auto;

写个简单的代码来理解

<style>
  .word{    width: 100px;    height: 30px;    background: #E5E5E5;    text-align: center;    line-height: 30px;    font-size: 14px;
    }</style><div class="word">
    <p>优秀</p></div>

webp

文字居中

优秀这两个字在div中妥妥居中。

水平居中

水平居中分两种情况

one:定宽块元素水平居中
定宽 + 块元素
来看看具体的代码

.wrap{width:200px;
     height:200px;
     border:1px solid red;
     margin:0 auto;} //宽度必须给值<div class="wrap"></div>

two:不定宽块元素水平居中

1.改变为行内元素,然后使用text-align:center处理,多用于不定项导航的ul的居中

.nav{text-align:center;}
.nav ul{display:inline;}
<div class="nav">
    <ul>
        <li>1111111</li>
        <li>2222222</li>
    </ul>
</div>

2.父元素浮动left:50%;
同时要设置position:relative(给子元素相对定位一个参考)
子元素相对定位position:relative;left:-50%;

.wrap{position:relative;
     left:50%;
     float:left;}
.box{position:relative; 
     left:-50%;}
<div class="wrap">    <div class="box">一个子级盒子</div><div>

垂直居中

垂直居中也分两种情况
one:块级元素垂直居中,子元素知道具体宽高
设置top:50%,这个块元素的最上边为垂直居中的位置,但是这样整体的内容并不是垂直居中,所以要设置margin-top: -2/父宽 px; //为高度的一半
这样这个块元素又相对于自身最上面向上又移动了自身的50%,因此就垂直居中了。

.wrap {  //父元素}
.wrap .content {
  position: absolute;
  width: 100px;
  heigth: 100px;
  top: 50%;
  margin-top: -50px; //为高度的一半}

*** two:子元素不知道具体宽高 ***

这种情况有三种方法

第一种借助table布局;
第二种是借助translate的transform属性:

.wrap {  position: relative;
}.wrap .content {  position: absolute;  top: 50%;  transform: translateY(-50%);
}

第三种就是用flex布局,非常的简单,代码如下:

.wrap{  display: flex;  flex-direction: column;  justify-content: center;
}

万能居中方法

首先移动子元素高度(宽度)的一半:left:50%;(top:50%;)
再移动父元素高度(宽度)的一半:margin-left:-宽/2;(margin-top:-高/2;)
前提是必须要知道子元素的宽高

.wrap{
    width: 200px;
    height: 200px;
    background-color: lightskyblue;
    position: relative;
     }
.box{
    width: 100px;
    height: 100px;
    background-color: hotpink;
        position: absolute;
    left:50%;
    margin-left: -50px;         
    }    
<div class="wrap">
      <div class="box">一个子级盒子</div></div>

webp

万能居中

绝对居中

子元素必须比父元素小,子元素宽高也必须要知道

.wrap{
    width: 200px;
    height: 200px;
    background-color: lightskyblue;
    position: relative;
     }
.box{
        width: 100px;
    height: 100px;
    background-color: hotpink;
    position: absolute;
    top: 0;
    right: 0;
        bottom: 0;
        left: 0;
        margin: auto;
        overflow: auto;
 }
<div class="wrap">
       <div class="box"></div>
</div>

webp

绝对居中

可能总结的也不太齐全,会慢慢补全。



作者:Passerbylll
链接:https://www.jianshu.com/p/397f9794c003


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消