css中不定宽高的元素居中布局怎么解决-成都快上网建站

css中不定宽高的元素居中布局怎么解决

本篇内容介绍了“css中不定宽高的元素居中布局怎么解决”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

10年的马山网站建设经验,针对设计、前端、开发、售后、文案、推广等六对一服务,响应快,48小时及时工作处理。网络营销推广的优势是能够根据用户设备显示端的尺寸不同,自动调整马山建站的显示方式,使网站能够适用不同显示终端,在浏览器中调整网站的宽度,无论在任何一种浏览器上浏览网站,都能展现优雅布局与设计,从而大程度地提升浏览体验。成都创新互联公司从事“马山网站设计”,“马山网站推广”以来,每个客户项目都认真落实执行。

1. 水平居中

css中不定宽高的元素居中布局怎么解决

公共代码:

html:


    parent
    
             child     

css:

html, body {
    margin: 0;
    width: 100%;
    height: 100%;

    .parent {
        width: 100%;
        height: 100%;
        background: #fac3fa;
        
        .child {
            width: 50%;
            height: 50%;
            background: #fe9d38;
        }
    }
}

方案一: text-align(父) + inline-block(子)

代码:
css:

.parent {
    text-align: center;

    .child {
        display: inline-block;
    }
}

方案二: 块级元素 + margin: 0 auto;

.child {
    display: block; // 非块级元素时设置
    margin: 0 auto;
}

方案三: absolute + transform

.parent {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
}

方案四: flex

注: 由于使用flex的关系, 这里去掉了 parent 和

.parent {
    display: flex;
    justify-content: center;
}

2. 垂直居中

css中不定宽高的元素居中布局怎么解决

公共代码:
html:


    

css:

html, body {
    margin: 0;
    width: 100%;
    height: 100%;
}
.parent {
    display: table-cell;
    width: 800px;
    height: 500px;
    background: #fac3fa;

    .child {
        width: 50%;
        height: 50%;
        background: #fe9d38;
    }
}

方案一: table-cell(父) + vertical-align(子)

.parent {
    display: table-cell;
    vertical-align: middle;
}

方案二: absolute + transform

.parent {
    position: relative;
    
    .child {
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    }
}

方案三: flex

.parent {
    display: flex;
    align-items: center;
}

3. 水平垂直居中

css中不定宽高的元素居中布局怎么解决

公共代码同[垂直居中]

常用方案一: absolute + transform

.parent {
    position: relative;
    
    .child {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
    }
}

常用方案二: flex

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

“css中不定宽高的元素居中布局怎么解决”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!


网站名称:css中不定宽高的元素居中布局怎么解决
地址分享:http://kswjz.com/article/gscdoc.html
扫二维码与项目经理沟通

我们在微信上24小时期待你的声音

解答本文疑问/技术咨询/运营咨询/技术建议/互联网交流

其他资讯