How to Use CSS in PHP echo with code example

In this article, we will discuss different methods of how to use CSS in PHP echo with some good examples. The PHP echo method can be used to return HTML to the browser, as you may already know. However, have you ever considered whether it can return CSS? The answer is yes but you will be learning in detail all of the possibilities in this article.

Method1: How to Use CSS in PHP Echo with Style Attribute

You can use the <p> the tag inside the PHP echo statement to add text content. In this tag, you have to add a style attribute within which you can mention CSS as given below:

Example:

<!DOCTYPE html>
<html>
<body>

<?php
echo "Welcome to Softhunt.net";
echo "<p style='color:red;'>This is a text in PHP echo.</p>";
?>

</body>
</html>

Output:

CSS in PHP echo img1

The above example shows the output that changes the appearance of the text content after adding the CSS. You can add as much CSS to it as you want to include.

Method2: Add CSS in a Class and Include the Class in PHP Echo

You can mention as many CSS as you want in a class. After that, add the CSS class to the text content with <p> tag in PHP echo statement as given below:

Example:

<!DOCTYPE html>
<html>
<body>

<style>
.mycss{
	color: white;
    border:1px solid #000;
    background: black;
    padding: 10px;
}
</style>

<?php
echo "Welcome to Softhunt.net";
echo "<p class='mycss'>This is a text in PHP echo.</p>";
?>

</body>
</html>

Output:

img2

You have to first add as many CSS as you want in a CSS class. The above example added 4 CSS properties in a class to style the text content.

Method3: Use Double Quotes and Escape Using Backslash

In addition to the above methods, you can add CSS class in the PHP echo a statement using the double-quotes. After that, you have to escape the quotes using the slash (\) symbol as given in the example below:

Example:

<!DOCTYPE html>
<html>
<body>

<style>
.mycssquote{
	color: white;
    background: black;
    border:1px solid red;
    padding: 5px;
}
</style>

<?php
echo "Welcome to Softhunt.net";
echo "<p class=\"mycssquote\">This is a text in PHP echo.</p>";
?>

</body>
</html>

Output:

img3

The above example uses the double quotes (” “) escaped using the backslash (\) symbol.

That’s all for this article if you have any confusion contact us through our website or email us at [email protected] or by using LinkedIn

Suggested Articles:

  1. How to Use PHP in HTML Pages
  2. Automatically Refresh or Reload a Page using jQuery Code Example

Leave a Comment