加入收藏 | 设为首页 | 会员中心 | 我要投稿 银川站长网 (https://www.0951zz.com/)- 云通信、基础存储、云上网络、机器学习、视觉智能!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

CSS盒子水平居中有几种方案 代码是什么

发布时间:2023-09-23 12:43:54 所属栏目:语言 来源:
导读:这篇文章主要介绍了“CSS盒子水平居中有几种方法,代码是什么”相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇CSS盒子水平居中有几种方法,代码是什么文章都会有所收获,下

这篇文章主要介绍了“CSS盒子水平居中有几种方法,代码是什么”相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇CSS盒子水平居中有几种方法,代码是什么文章都会有所收获,下面我们一起来看看吧。

在CSS中如何让盒子水平居中是很常见的面试题,盒子居中是相对于父元素来说的,因此我们让盒子居中时,往往采用嵌套的方式,让父盒子套着子盒子 。

在父子盒子嵌套下,让子盒子居中的方式:

第一种方法:margin: 0 auto,使用边框,但是margin使用会影响其他盒子的使用,不太推荐使用;

第二种方法:position, 使用定位,子绝父相,再left:50%,margin-left:负的盒子宽度的一半,这是最常用的方法;

第三种方法:flex,弹性布局,让子盒子居中,但是样式要写在父盒子中,display:flex,just-content:center;

第四种方法:在position基础上,把margin-left换成CSS3中的transform:translate(-50px);

第五种方法:在position的基础上,只保留子绝父相,然后在子盒子中加上margin:auto、left:0、right:0;

补充:在第五种方法上,加上top:0,bottom:0,可以实现垂直和水平都居中

<div id="father">

<div id="son"></div>

</div>

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

}

</style>

使用margin实现水平居中:

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

margin: 30px auto; /* 让父元素相对于body居中 */

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

margin: 0 auto;/* 让子元素相对于father居中 */

}

</style>

使用定位,子绝父相,再left:50%,margin-left:负的盒子宽度的一半:

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

margin: 0 auto;

position: relative;

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

position: absolute;

left: 50%;

margin-left: -50px;

}

</style>

flex,弹性布局,让子盒子居中,但是样式要写在父盒子中:

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

margin: 0 auto;

display: flex;

justify-content: center;

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

}

</style>

在position的基础上,只保留子绝父相,然后在子盒子中加上margin:auto、left:0、right:0:

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

margin: 0 auto;

position: relative;

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

position: absolute;

margin: auto;

left: 0;

right: 0;

}

</style>

以上几种方法都可以实现盒子的水平居中,如果大家有其它优(奇)秀(葩)方法,欢迎交流鸭!

第五种方法补充:再加上top:0,bottom:0可以实现水平和垂直都居中 :

<style>

#father{

width: 400px;

height: 200px;

border: 3px solid pink;

margin: 0 auto;

position: relative;

}

#son{

width: 100px;

height: 100px;

border: 2px solid red;

position: absolute;

margin: auto;

left: 0;

right: 0;

top: 0;

bottom: 0;

}

</style>

关于“CSS盒子水平居中有几种方法,代码是什么”就介绍到这了,如果大家觉得不错可以参考了解看看,如果想要了解更多,小编每天都会为大家更新不同的知识。

(编辑:银川站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章