随笔- 191  文章- 0  评论- 3  阅读- 59016 

垂直居中:vertical-align :

1、只能作用在子元素 display 值为 inline,inline-block,inline-table,table-cell 的元素上,

2、子元素 设置vertical-align

3、父元素高度是由line-height决定(不要乱给父元素添加height)

复制代码
<div class="father">
      <span class="son">a</span>
</div>

 <style>
      .father {
        width: 200px;
        line-height: 200px;
      }
      .son {
        // display: inline-block; // span元素默认inline,p元素默认 block(即p标签需要设置display,span不用设置)
        vertical-align: middle;
      }
</style>
复制代码

水平居中:text-align:

1、父元素设置text-align:center

2、子元素 设置 display inline 、inline-block

复制代码
<div class="father">
      <span class="son">a</span>
</div>

 <style>
      .father {
        width: 200px;
        height: 200px;
        text-align: middle;
      }
</style> 
复制代码

水平居中: margin 0 auto:

1、子元素display block

2、子元素设置margin: 0 auto;

注意:子元素不可以是inline-block,inline

复制代码
<div class="father">
      <span class="son">a</span>
</div>

 <style>
      .father {
        width: 200px;
        height: 200px;
      }
     .son{
   display: block; margin: 0 auto; } </style>
复制代码

水平+垂直居中:absolute+margin auto 

1、父元素设置 position: relative;

2、子元素设置

        position: absolute;
        margin: auto;
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
复制代码
<div class="father">
      <span class="son">a</span>
</div>

<style>
      .father {
        position: relative;
      }
      .son {
        position: absolute;
        margin: auto;
/*水平居中*/
left: 0; right: 0;
     /*垂直居中*/ top: 0; bottom: 0; } </style>
复制代码

水平+垂直居中:absolute+transform

复制代码

<div class="father">
      <span class="son">a</span>
</div>
<style>
.father{ position: relative; } .son{ position: absolute; /*水平居中*/ left: 50%; transform: translate(-50%,0); /*垂直居中*/ top: 50%; transform: translate(0,-50%); /*水平垂直居中*/ /* top: 50%; left: 50%; transform: translate(50%, 50%); */ }
</style>
复制代码

水平+垂直居中:table

父元素设置 display: table;

子元素设置display: table-cell; 

 

注意:子元素会占满父元素,多个子元素会平分父元素的宽度,这里面水平和垂直居中的是孙子元素,不是子元素,

并且水平和垂直居中属性需要设置在子元素身上!!!

孙子元素display 为 inline,inline-block

 

复制代码
<div class="father">
  <div class="son">
  <span>a</span>
</div> <div class="son">
<span>a</span>
</div>
</div>

<style>
      .father {
        display: table;
      }
      .son {
        display: table-cell;
        vertical-align: middle;/*垂直居中孙子元素*/
        text-align: center;/*水平居中孙子元素*/
      }
</style>
复制代码

 

水平+垂直居中:flex

父元素设置 display: flex;

复制代码
<div class="father">
    <div class="son">
        a
    </div>
</div>

<style>
.father{
    display:flex;
    justify-content:center;/*水平居中*/
    align-items:center;/*垂直居中*/
}
</style>
复制代码

 

 posted on   laremehpe  阅读(6)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示