web前端实现水平垂直居中、position、relative、absolute、transform、translate、auto、display、flex、justify、align、center


1、文本水平垂直居中

HTML

<div class="text_box">
    <span>文本实现垂直水平居中</span>
</div>

CSS

.text_box {
    
    
    width: 230px;
    height: 60px;
    /* 水平居中 */
    text-align: center;
    /* 垂直居中 */
    line-height: 60px;
    background-color: #ccc;
}

2、使用定位实现水平居中/宽高未知

2.1、transform

HTML

<div class="unknown_wh_box">
    <div></div>
</div>

CSS

.unknown_wh_box {
    
    
    position: relative;
}

.unknown_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

2.2、margin

HTML

<div class="unknown_wh_box">
    <div></div>
</div>

CSS

.unknown_wh_box {
    
    
    position: relative;
}

.unknown_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
}

3、使用定位实现水平垂直居中/宽高已知

3.1、transform

HTML

<div class="known_wh_box">
    <div></div>
</div>

CSS

.known_wh_box {
    
    
    width: 70%;
    height: 300px;
    position: relative;
    background-color: #aaa;
}

.known_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}

3.2、margin

HTML

扫描二维码关注公众号,回复: 14219544 查看本文章
<div class="known_wh_box">
    <div></div>
</div>

CSS

.known_wh_box {
    
    
    width: 70%;
    height: 360px;
    position: relative;
    background-color: #aaa;
}

.known_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
}

4、弹性布局实现水平垂直居中

4.1、未知宽高

高度会自动被撑开,且紧贴子容器。


HTML

<div class="unknown_wh_box">
    <div></div>
</div>

CSS

.unknown_wh_box {
    
    
    display: flex;
    justify-content: center;
    align-items: center;
}

.unknown_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
}

4.2、已知宽高

HTML

<div class="known_wh_box">
    <div></div>
</div>

CSS

.known_wh_box {
    
    
    width: 70%;
    height: 360px;
    background-color: #aaa;
    display: flex;
    justify-content: center;
    align-items: center;
}

.known_wh_box>div {
    
    
    width: 230px;
    height: 230px;
    background-color: #ccc;
}

猜你喜欢

转载自blog.csdn.net/weixin_51157081/article/details/124844634