前端开发 \ CSS \ 自适应宽高的盒子中文本垂直水平居中

自适应宽高的盒子中文本垂直水平居中

总点击40
简介:问题:如何让span中的文字在div中垂直水平居中? 方法一:display:table;和display:table-cell;

自适应宽高的盒子中文本垂直水平居中

问题:如何让span中的文字在div中垂直水平居中?

方法一:display:table;和display:table-cell;

给父元素div设置position: absolute;display:table;  这样,div就会撑满整个浏览器屏幕;

给需要居中的元素span设置display:table-cell; vertical-align:middle;  这样,span就会撑满div,span中的文字也在span中垂直居中,再用text-align: center;让文字在span中水平居中。

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

html,body{

margin: 0;

}

.father{

width: 100%;

height: 100%;

background-color: yellow;

position: absolute;

display: table;

}

.son{

background-color: lawngreen;

display: table-cell;

vertical-align: middle;

text-align: center;

}

</style>

</head>

<body>

<div class="father">

<span class="son">我是测试文本</span>

</div>

</body>

</html>方法二、不用position: absolute;,而是给html,body设置显性百分比100%。然后给父元素设置display:table,给需要居中的元素设置display:table-cell;vertical-align:middle;

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

html,body{

margin: 0;

height: 100%;

}

.father{

width: 100%;

height: 100%;

background-color: yellow;

display: table;

}

.son{

background-color: lawngreen;

display: table-cell;

vertical-align: middle;

text-align: center;

}

</style>

</head>

<body>

<div class="father">

<span class="son">我是测试文本</span>

</div>

</body>

</html>方法三、弹性布局flex

给需要其内容居中的元素div设置display:flex;justify-content:center;align-items:center;,这样span在div中垂直水平居中,span是行内元素,文字撑满了span,所以文字在div中也处于垂直水平居中。


如果span转块,有了宽高,那再给span设置display:flex;justify-content:center;align-items:center;让文字在span中垂直水平居中。

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Title</title>

<style>

html,body{

margin: 0;

height: 100%;

}

.father{

width: 100%;

height: 100%;

background-color: yellow;

display: flex;

/*水平居中*/

justify-content: center;

/*垂直居中*/

align-items: center;

}

.son{

background-color: lawngreen;

}

</style>

</head>

<body>

<div class="father">

<span class="son">我是测试文本</span>

</div>

</body>

</html>

小技巧tips:

设置高度、宽度百分比时,百分比是相对于父元素来确定,承接父元素的百分比是相对于浏览器屏幕大小来确定,必须给html,body设置显性百分比100%。

意见反馈 常见问题 官方微信 返回顶部