居中问题

不同的情形下居中有很多不同的方法,以下探讨了不同情况下的居中解决办法。
1.水平居中
1>行内元素
要使一个拥有块级容器的行内元素居中,可以使用:

text-align: center;

适用:inline、inline-block等重点内容重点内容

2>块级元素
通过设置其margin-left和margin-right分别为auto可以实现居中

margin: 0 auto;

3>多个块级元素的居中
方法一:将块级元素设置为inline-block:

<div id="container">
<body>
<div id="left">
</div>
<div id="right">
</div>
<div id="middle">
</div>
</div>

#container{ width:100%; text-align:center; background:#37FF9B; }
#left{ height:300px; width:200px; background:#999; display:inline-block; }
#right{ height:200px; width:200px; background:#999; display:inline-block; }
#middle{ height:100px; width:200px; background:#999; display:inline-block; }

这里写图片描述
方法二:利用flex布局:

{
  display: flex;
  justify-content: center;
}

这里写图片描述

2.垂直居中
1>行内元素
单行:
方法一:设置上下相等的padding即可
方法二:设置行高line-height

2>块级元素
知道居中元素的高度:

<div>
     <p></p>
</div>

div{
     height:200px;
     width:200px; 
     background:#37FF9B; 
     position:relative; 
     }
p{
    width:100%;
    height:80px;
    position:absolute;
    top:50%;
    margin-top:-40px;
    background:#DCE047;
    }

这里写图片描述

不知道居中元素的高度:
方法一:

<div>
     <p></p>
</div>

div{
     height:200px;
     width:200px; 
     background:#37FF9B; 
     position:relative; 
     }
p{
    width:100%;
    height:80px;
    position:absolute;
    top:50%;
    transform: translateY(-50%);
    background:#DCE047;
    }

利用transform属性使其上移自身的一半高度

方法二:
使用flex布局:

<div>
     <p></p>
</div>

div{ 
     display:flex;
     flex-direction:column;
     justify-content:center;
     height:200px;
     width:200px; 
     background:#37FF9B; 
     }
p{
    width:100%;
    height:80px;

    background:#DCE047;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值