html元素居中

一、不定宽高元素居中

  1. table
HTML:
<div class="father">
    <div class="son">
        this is content
    </div>
</div>

CSS:
.father {
    display: table;
}

.son {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
  1. absolute, transform
HTML:
<div class="father">
    <div class="son">
        is this OK?
    </div>
</div>

CSS:
.father {
    position: relative;
}

.son {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
  1. css3 flex
HTML:
<div class="container">
    <div class="inner">
        this is a box fixed in center of screen<br>The second line
    </div>
</div>

CSS:
.father{
    display: flex;
    align-items: center;
    justify-content: center;
}
  1. :before和display:inline-block
HTML:
<div class="father">
    <div class="son">
        this is a box fixed in center of screen<br>The second line
    </div>
</div>

CSS:
.father {
    text-align: center;
    background-color: red;
}

.father:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}

.son {
    display: inline-block;
}
  • 这里需要注意文字在多行的情况下,新换的一行将起始于:before的下一行,所以会在:before的100%高度下面,导致被顶出.father。但是如果把文字放在.son 里面,再让.son 为inline-block,就可以使.son 和:before处于同一基线,这样就让整个.son 处于垂直居中的状态。
  1. vw vh和translate
HTML:
<div class="inner">
    this is a box fixed in center of screen
</div>
CSS:
.inner {
   position:fixed;
   top: 50vh;
   left: 50vw;
   transform: translate(-50%, -50%); 
}
  • vh和vw是两个比较偏的单位,是指“viewport的height和width的1%”,比如说50vh就是当前视口(窗口的高度,实验中包含了滚动条)高度的50%。

二、固定宽高元素居中

  1. fixed
position: fixed;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
width: 800px;
height: 400px;
  • fixed方案适合在整个窗口实现居中。fixed会使元素脱离网页,因此在内容流中不适用。
  1. absolute
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
width: 300px;
height: 350px;
  • 绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样。
  • 再用transform向左(上)平移它自己宽度(高度)的50%
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,686评论 1 92
  • 收听音频,戳链接,旧号itclan已暂停使用,欢迎关注微信itclanCoder公众号可收听更多音频 前言 关于网...
    itclanCoder阅读 12,531评论 3 30
  • CSS 是什么 css(Cascading Style Sheets),层叠样式表,选择器{属性:值;属性:值}h...
    崔敏嫣阅读 5,346评论 0 5
  • 学会使用CSS选择器熟记CSS样式和外观属性熟练掌握CSS各种选择器熟练掌握CSS各种选择器熟练掌握CSS三种显示...
    七彩小鹿阅读 11,428评论 2 66
  • 植物的象征意义 植物常常被用来表示生命周期、死亡、再生。植物还可以开花结果,而果实是一种能量的象征,来访者使用植物...
    潼宝的开心果阅读 1,092评论 0 0