css 怎么设置文字在图片上并居中

html-css016

css 怎么设置文字在图片上并居中,第1张

1、首先,打开html编辑器,新建html文件,例如:index.html。

2、在index.html中的<style>标签中,输入css代码:span {position: absolutetop: 45pxleft: 180px}。

3、浏览器运行index.html页面,此时成功通过css设置了文字在图片上面居中显示。

文字在图片上显示

<!DOCTYPE html>

<html>

<head>

<title></title>

<meta charset="UTF-8">

<style>

#abox{

position:relative/*容器相对定位*/

width:300px/*宽度300px*/

margin:0 auto/*横向居中*/

}

#abox img{

width:300px/*宽度300px*/

}

span{

position:absolute/*文字容器绝对定位*/

display:block/*span转为块元素*/

width:100%/*宽度相对于父容器100%*/

text-align:center/*文字居中*/

top:0/*距离父容器顶部0*/

left:0/*距离父容器左侧0*/

color:red/*文字颜色红色*/

font-size:18px/*文字大小既文字高度18px*/

font-weight:bold/*文字加粗*/

}

</style>

</head>

<body>

<div id="abox"><!--容器,相对定位-->

  <img src="123.jpg"><!--图片-->

  <span>我要显示文字</span><!--文字,绝对定位-->

</div>

</body>

</html>

、在div中,使用p标签创建一行文字,使用img创建一张图片。

2、设置div标签的class属性为mydiv。

3、在css标签内,通过class设置div的样式,设置它的宽度为400px,边框为1px,并将display属性设置为flex,实现flex布局。

4、在css标签内,将align-items属性设置为center(水平居中),将justify-content属性设置为space-between(两端对齐)。

5、在浏览器打开test.html文件,查看实现的效果。