元素居中的方式

1.单行文本水平居中

说明:

只针对块元素中的行内元素,或者 行内块元素,使用text-align:center; 属性

HTML:

<div class="box">
        <span>
            我是文字
        </span>
</div>

CSS:

.box {
    background-color: pink;
    height: 200px;
    width: 200px;
    text-align: center;
    }

图示:

image-20220307113126525

2.单行文本水平垂直居中

说明:

使块元素中的行内元素水平垂直居中

垂直居中:line-height: 取值盒父元素高度一样

CSS:

.box {
    background-color: pink;
    height: 200px;
    width: 200px;
    text-align: center;
    line-height: 200px;
}

image-20220307113630172

3.块元素水平居中

说明:

水平居中:块元素有固定宽度(宽度不为100%)

margin:0 auto;

HTML:

<div class="box">
    <div class="box2"></div>
</div>

CSS:

.box {
    background-color: pink;
    height: 200px;
    width: 200px;
}
.box2 {
    width: 100px;
    height: 100px;
    background-color: yellow;
    margin: 0 auto;
}

图示:

image-20220307135310560

4.块元素垂直居中

1.定位(position)

CSS:

.box {
    background-color: pink;
    height: 300px;
    width: 300px;
	/*相对定位*/
    position: relative;
}
.box2 {
    width: 100px;
    height: 100px;
    background-color: yellow;
	/*绝对定位*/
    position: absolute;
	/*垂直方向 向下移动相对于父盒子的25%*/
    top: 50%;
	/*水平方向 向右移动相对于父盒子的25%*/
    left: 50%;
	margin-left: -50px;
	margin-top: -50px;
}

图示:

image

2.弹性盒子(display:flex)

CSS:

.box {
    background-color: pink;
    height: 200px;
    width: 200px;
	/* 设置为弹性盒子 */
    display: flex;
}
.box2 {
    width: 100px;
    height: 100px;
    background-color: yellow;
    /* 只有一个元素时,使用margin:auto */
    margin: auto;
}

图示:

image-20220307142639335

posted @ 2022-03-07 14:31  秋弦  阅读(73)  评论(0编辑  收藏  举报