首页 > 解决方案 > 如何制作包含背景图像的 CSS 类

问题描述

我想创建一个 CSS 类,该类将包含应用到它的元素周围的背景图像,所以如果我将它应用于段落元素(p),它将把图像放在元素上并将文本写入图像中,我尝试了几次,但我找不到也无法创建它。这是我到目前为止所拥有的:

.paragraph {
        background-image: url("../../res/images/Plate.png");
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
    }

这就是我的样子(图像的顶部和底部不显示):

在此处输入图像描述

代码:

body {
background-image: url("https://cdn.discordapp.com/attachments/704268108759695460/708284755820412938/Text-Effect-No1-bkg.png");
background-repeat: no-repeat;
background-size: cover;
}

.title {
	font-family: Accuratist, Ariel, serif;
	font-style: normal;
	color: orange;
	font-size: 250%;
	text-align: center;
}

.subtitle {
	font-family: Accuratist, Airel, serif;
	font-style: normal;
	color: orange;
	font-size: 200%;
	text-align: center;
}

.paragraph {
  	background-image: url("https://cdn.discordapp.com/attachments/704268108759695460/708284745024405504/Text-Effect-No1-Plate.png");
  	width: 75%;
  	display: block;
  	margin: auto;
  	background-position: center;
  	background-repeat: no-repeat;
  	background-size: cover;
	font-family: Accuratist, Ariel, serif;
	font-style: normal;
	color: orange;
	font-size: 100%;
	text-align: center;
	align-self: center;
}
<html>
<head>
<meta charset="ISO-8859-1">
<title>Something</title>
</head>
<body>
	<jsp:include page="NavBar.jsp"></jsp:include>
	<h1 class="title">Title</h1>
	<h2 class="subtitle">Sbtitle</h2>
	<br/>
		<p class="paragraph"><br/>
			Hello World<br/>
			The image extends downards whenever I line down.<br/>
			But if I write an extrememly long line, the words will get out of the image's boundires and rip it looks really really weird as you can see.<br/>
			Also, the top and botton of the image does not show up (I will show you the original image) which is weird considering I used cover on bg size...<br/><br/></p>
</body>
</html>

笔记:

由于图像在我的电脑上,所以我没有在这里使用 css 中的路径,我只是将它们放在不和谐上并使用链接大声笑,但路径是正确的,因为图像确实显示了 soo.. 是的。

原图:

在此处输入图像描述

标签: htmlcss

解决方案


如果我正确理解了您的要求,这是您想要的吗?

.paragraph {
        background-image: url("http://placekitten.com/301/301");
        background-position: center;
        background-repeat: no-repeat;
        background-size: cover;
        color:yellow;   
        font-size:20px;
        height:50px; /* this is just to show the image fit-in */
    }
<p class="paragraph">
This is paragraph
</p>


推荐阅读