Style MySQL table with CSS

CSS Variables with PHP

When people are asked about features they would like to CSS, “variables” always seems to come up. Whether or not this is a good idea is still something I personally haven’t decided on, but I’d lean toward yes. Regardless, using PHP, it is trivially easy to use variables in CSS. This is certainly not a new trick, but I’ve never specifically covered it so I thought I ought to.

Below all that PHP stuff, you can just commence regular CSS writing, only you can intermix some PHP to spit out those variables.

#header < background: url("/images/header-bg.png") no-repeat; > a < color: ; > . ul#main-nav li a < color: ; >

Extend the power / Other ideas

  • While you are at it, might as well compress the CSS with PHP.
  • Theoretically you could pull the user agent and attempt to do browser-specific CSS, but that is littered with problems and not recommended.
  • Pull the date/time, and perhaps change some stuff on your site for the different seasons or time of day.
  • Generate a random number, test the result, use it to set a random background image on your header.

I did a totally static test page and it worked fine, then I tried this same technique within a WordPress site and no dice. The solution for me was to leave the file named style.css, and use .htaccess to parse it as PHP. Just make sure this code is in the .htaccess file (Apache servers only) at the same directory level as the CSS file. Then just use PHP inside it as you would any other PHP file.

Читайте также:  Закрасить фон ячейки таблицы html

Carlo DeAgazio wrote in to say this works for him in WordPress:

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

Hey Chris, I was playing with this idea the other day, but never had time to look deep into it. I have one question: what can you tell me about perfomance? I suppose it´s slower than a pure css stylesheet, but it´s much slower or you cant even notice the difference? Thanks for your time and for this very interesting post.

Really interesting concept. I could see it being very useful in a corporate setting like where I work now. It would be easy to change colors/fonts if the corporate branding went in a new direction.

@Martin There’s no reason why it should be slower than pure css: The moment the css is delivered to the client from the server, it has become pure css already. Don’t forget that any php code is executed on the server before anything happens in the browser. If your code is really complex, you might notice some kind of downside on performances because it would take some time for the server to execute the script. However I don’t see this happening at all with this kind of method. My 2¢

I’m sure there is some cost as the server has to process it and then deliver it, rather than just deliver it – but we’re talking microseconds here. When I used this method, it wasn’t noticeably slower than pure CSS.

Thanks for your answers, both O and LineIn. What you´ve wrote seems very coherent, so I think its just a matter of give this a try!

There is actually a performance issue. As far as I know, these php-parsed stylesheets do not get cached by the client. So the stylesheet is processed everytime it is called by the client.
Correct me if I am wrong.
You could probably set an “expires” header in php but I’m not that into HTTP myself. Any ideas?

Actually you don’t need to work around the caching problem. Since you aren’t really doing anything dynamic inside the script you could just run the following from the command line on mac/linux: php myStyles.php > myStyles.css Then link the the css file we just generated. You’ll have to recompile the css file each time you change it, so it’s only really useful once you’re done testing.

There are some major performance issues. You should not use PHP or any application tier logic to generate static content at runtime. I go into all the performance issues here: http://bit.ly/4suKSp

Another way to do this, albeit not very effective, is to embed the styles directly in document and have php echo the variables there. A more useful variant of this method is applying it to JavaScript. I once utilized this when I had to position an element with JS generated CSS, when the position was reliant upon the submitting of a php form.

The biggest reason I’d want to use CSS Variables is class inheritance. e.g. for sprites. .sprite <
background-url…
text-indent…
> .header extends .sprite
.header <
background-position…
> .submit extends .sprite
.submit <
background-position…
> Which saves us from having to put things like
input submit” and littering HTML with class names. I’d love to see something like that using this method. Nicole Sullivan goes into some depth about this here: http://www.stubbornella.org/content/2009/11/09/css-wish-list/

you should take a look at the github project page of oocss (http://github.com/stubbornella/oocss) . there you can find a lot of object oriented css code, which can be used like this “input submit” ” .
everybody knows that this is not the best way to do it but it’s actually a concept that should find it’s way into the css specs. of course the project is open to any kind of contributions (ideas, comments, code, …)

Well, there is an ‘Object Oriented CSS’ out there but am not sure if it allows inheritance.. (though I believe it should) Have to study it.. Darn, these technologies are developing at a very past pace… No sooner I learnt CSS 2.0 than new versions of CSS i.e. CSS 3.0 and Object Oriented CSS came out in the market 😛

You could also use something like Scaffold to do this, which also adds a number of other benefits (caching, nested selectors, compression, etc.).

Scaffold would be what I’d use if I were to go down this route. I’ve tried it out but unfortunately it doesn’t work on my WAMP set-up.

Chris, Since you’re the WordPress pro, I thought I’d ask. Is there an easy way to work this into a WordPress theme? A lot of times when I sell a theme I get requests to change colors, etc, by people who don’t know CSS. If all they had to do was change a few variables at the top then it would be easy to explain.

I’ve always been perplexed by why this enhancement is so desired because this functionality already exists. Don’t you have have the ability to have psuedo variables with the ability of specifying multiple classes?

That means you’d have to define style in the HTML. I’m not going to explain why that’s bad, google knows 😉

This is exactly what I was going to post. I found it very liberating to quickly create divs say div h200px float-l bgcolor1 textcolor3 font1″ I don’t see why this is any worse or heavier than giving an element an id and creating a style chunk for it when I was playing around with this I was able to do a lot more with less code since you can declare a bunch of design specific variables and then just apply them to whatever element you desire easily. It also sets up addClass and toggleClass well with jQuery. I would like to know the downsides to this method though. Obviously when working with dynamically generated content things could get stickier. I noticed facebook uses a lot of these descriptor classes in their markup.

The WordPress theme Mandigo uses this technique. The style sheet is style.css.php. Interesting theme, but this makes it difficult to modify the theme at the code level. The end user has quite a bit of control using the admin theme options.

ohhh. interesting. that would be a big draw if users could set color codes in an admin panel I think.

Источник

Use CSS Style in PHP

Use CSS Style in PHP

  1. Use CSS in a PHP-Only File
  2. Use CSS in a PHP+HTML File
  3. Use Inline CSS in PHP echo Statements

This article will teach you three methods that’ll help you use CSS styles in PHP.

The first method is via a PHP-only file, and the second is to embed PHP in an HTML+CSS file. Then the third method will use inline CSS in PHP echo statements.

Use CSS in a PHP-Only File

A standard HTML file can embed CSS styles in the element or link to an external CSS file. By default, this CSS file will have the css extension, but it can also have the php extension.

This means you can write CSS code, save it as a PHP file and link it to your HTML. In this PHP file, you can do more than what you’ll do in a CSS file; you can write PHP code.

First, you can define a PHP code block with CSS property and values stored as variables. Then outside the PHP block, you can write normal CSS that’ll use the variables as values of CSS properties.

We’ve done that in the following; save it as styles.php .

php  // The "header" is the most important part of  // this code. Without it, it will not work.  header("Content-type: text/css");   $font_family = 'Trebuchet MS, Verdana, Helvetica';  $font_size = '1.2em';  $background_color = '#000000';  $font_color = '#ffffff';   // Close the PHP code block.  ?> body   background-color: ;  color: ;  font-size: ;  font-family: ; > 

Save the following HTML, and ensure you’ve linked styles.php in the tag.

 html lang="en"> head>  meta charset="utf-8">  title>Webpage using CSS styles generated with PHPtitle>   link rel="stylesheet" type="text/css" href="styles.php">  head> body>  h1>Hello, We styled this page using CSS in a PHP file!h1>  h1>How cool is that?h1>  body>  html> 

Web page styled with CSS in PHP

Use CSS in a PHP+HTML File

HTML can use CSS via the tag or the tag, which can contain PHP in a dedicated PHP block. If the PHP code generates or manipulates HTML code, the linked CSS code can style the HTML.

For example, you can style the table using CSS if PHP pulls database records to make an HTML table. To show how to do this, create a database called my_website in MySQL.

Next, create a site_users table in my_website using the following queries.

CREATE TABLE site_users (  user_id INT NOT NULL AUTO_INCREMENT,  username VARCHAR(50) NOT NULL,  email VARCHAR(100) NOT NULL,  PRIMARY KEY (user_id)) ENGINE = InnoDB; 

Insert data into the site_users table.

INSERT INTO site_users (username, email) VALUES ('user_1', 'user_1@gmail.com');  INSERT INTO site_users (username, email) VALUES ('user_2', 'user_2@gmail.com');  INSERT INTO site_users (username, email) VALUES ('user_3', 'user_3@gmail.com'); 

Now, in the following, we have HTML, PHP, and CSS. The CSS is in the element; the PHP is in a PHP block within the HTML.

The PHP creates an HTML table using records from the site_users table. When the PHP generates the table, the CSS will style it.

    /* This CSS will style the table generated by PHP. */ table < border-collapse: collapse; width: 30em; font-size: 1.2em; >table, th, td < border: 2px solid #1a1a1a; >td,th < padding: 0.5em; >/* Create a striped table. */ tr:nth-child(even) < background-color: #f2f2f2; >/* General body styles. */ body  
query("SELECT * FROM site_users")->fetch_all(MYSQLI_ASSOC); // Get keys from the first row. $table_header = array_keys(reset($site_users)); // Print the table. echo ""; // Print the table headers. echo ""; foreach ($table_header as $value) < echo ""; > echo ""; // Print the table rows foreach ($site_users as $row) < echo ""; foreach ($row as $value) < if (is_null($value)) < echo ""; > else < echo ""; > > echo ""; > echo "
" . $value . "
NULL" . $value . "
"; ?>

PHP table styled with CSS

Use Inline CSS in PHP echo Statements

PHP works well with HTML and has the echo statement that can send HTML with inline CSS to the web browser. This is useful when debugging or sending large chunks of HTML to the web browser.

The following shows you how to use inline CSS with PHP echo . We define the text and store three colors in the $colors_array .

Then we use foreach to loop through the $colors_array , and we set the array element as the value of the inline CSS. When you run the code, the text appears three times with different colors.

php  $sample_text = "We generated this text color using inline CSS in PHP.";   $colors_array = ['red', 'green', 'blue'];   foreach ($colors_array as $value)   // Use inline CSS with PHP echo.  echo "

" . $sample_text . "

"
;
> ?>

A text styled using red, green, and blue

Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

Related Article — PHP CSS

Источник

Оцените статью