欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

个人笔记-css实现盒子模型水平居中和垂直居中

程序员文章站 2022-04-30 12:09:27
...

CSS实现盒子模型水平居中的方法

1、margin+width

适用于盒子的宽度是已知的


<div class="parent">

    <div class="child"></div>

</div>

.child {

    width: 50px;

    margin: 0 auto;

}

2、text-align+inline-block

适用于盒子的宽度是未知的


<div class="parent">

    <div class="child"></div>

</div>

.parent {

    text-align: center;

}

.child {

    display: inline-block;

}

3、float+position

适用于盒子的宽度是未知的


<div class="parent">

    <div class="between">

        <div class="child"></div>

    </div>

</div>

.between {

    position: relative;

    left: 50%;

    float: left;

}

.child {

    position: relative;

    right: 50%;

}

 

4、position

适用于盒子的宽度是未知的


<div class="parent">

    <div class="between">

        <div class="child"></div>

    </div>

</div>

.parent {

    position: relative;

}

.between {

    position: absolute;

    left: 50%;

}

.child {

    position: relative;

    right: 50%;

}

CSS实现盒子模型垂直居中的方法

1、position+transform


<div class="parent">

    <div class="child"></div>

</div>

.parent {

    position: relative;

    width: 200px;

    height: 200px;

}

 

.child {

    position: absolute;

    top: 50%;

    transform: translate(0%, -50%);

}

 

2、flex布局


<div class="parent">

    <div class="child"></div>

</div>

.parent {

    display: flex;

    align-items: center;

}

 

CSS实现盒子模型水平垂直居中方法

1、position+tranform


<div class="parent">

    <div class="child"></div>

</div>

.parent {

    position: relative;

}

 

.child {

    position: absolute;

    left: 50%;

    top: 50%;

    transform: translate(-50%,-50%);

}

2、position


<div class="parent">

    <div class="child"></div>

</div>

.parent {

    position: relative;

}

 

.child {

    position: absolute;

    top: 0;

    bottom: 0;

    left: 0;

    right: 0;

    margin: auto;

}

3、flex

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <span class="child"></span>
</div>
.parent {
	    	width: 500px;
		height: 500px;
		background-color: yellow;
		display: flex;/*子元素都会变成行内块级元素*/
		justify-content: center;
		align-items: center;/*单行垂直居中*/
		/*align-content: center; 多行垂直居中*/
	}

	.child {
		width: 100px;
		height: 100px;
		background-color: saddlebrown;
		margin-left: 10px;
	}