欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

在Web设计中,如何轻松实现中文文本与div元素的水平垂直居中?

最编程 2024-08-08 19:04:03
...
	//html
	<div class="box">
        <div class="box_bl">

        </div>
    </div>

实现box_bl容器的水平垂直居中

方法一

父级box设置positon:relative;(相对定位);子级box_bl设置 position: absolute;(绝对定位)top、bottom、left、right的值设为0,margin设置为auto。
代码如下:

//css
.box{
    width: 500px;
    height: 600px;
    background-color: black;
    position: relative;
}
.box .box_bl{
    width: 200px;
    height: 200px;
    background-color: brown;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

效果如下:
在这里插入图片描述

方法二(未知宽高)

不确定当前div的宽度和高度,父级box设置positon:relative;(相对定位);子级box_bl设置 position: absolute;(绝对定位)用 transform: translate(-50%,-50%);
代码如下:

//css
.box{
    width: 500px;
    height: 600px;
    background-color: black;
    position: relative;
}
.box .box_bl{
    width: 20%;
    height: 20%;
    background-color: brown;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%); 
}

效果如下:
在这里插入图片描述


简单常用的居中方法。

推荐阅读