水平垂直居中的集中方式

2020-04-01  本文已影响0人  大福爸爸_

css篇

水平垂直居中的集中方式

  1. js实现
  2. position
  3. flex
1. js实现
<!--html内容-->
<body>
    <div class='box' id='box'>
    我是内容
    </div>
</body>
// javascript
window.onload = () => {
    let {innerHeight: bodyHeight, innerWidth: bodyWidth} = window;
    let {offsetHeight: boxHeight, offsetWidth: boxWidth} = box;
    
    box.style.position = 'absolute';
    box.style.top = `${(bodyHeight - boxHeight) / 2}px`;
    box.style.left = `${(bodyWidth - boxWidth) / 2}px`;
}
2. position
html, body{
    height: 100%;
    overflow:hidden;
}
.box {
    width: 100px;
    height: 50px;
    /* 方式1 (必须知道宽高)*/
    positon: absolute;
    top: 50%;
    left: 50%;
    margin-top: -25px;
    margin-left: -50px;
    
    
        /* 方式2(兼容性差) */
    positon: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    
    
    /* 方式3(最普通) */
    display: flex;
    justify-content: center;
    aligh-item: center;
    
}

盒子模型

  1. 标准盒子模型(盒子宽高是内容高度-去除border和padding)
  2. 怪异盒子模型(盒子宽高就是内容加上border和padding的大小)
/* 标注盒子模型 */
box-sizing: content-box;
/* 怪异盒子模型 */
box-sizing: border-box;

上一篇 下一篇

猜你喜欢

热点阅读