美文网首页
html元素居中

html元素居中

作者: Macgx | 来源:发表于2018-08-15 08:56 被阅读10次

一、不定宽高元素居中

  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%

相关文章

网友评论

      本文标题:html元素居中

      本文链接:https://www.haomeiwen.com/subject/yolibftx.html