1

I want to add CSS that is dependent on some PHP variables in the code that is generated before a WP_Query loop. Basically I want to use uniqid and apply the ID to some elements and then add some media query rules for these elements, possibly as <style> tags. I've tried the following, but I'm not sure if style tags that are put in the <body> are ignored or not since this is not working.

$id = uniqid();

<style>
#<?php echo $id; ?> {
    background: red!important;
    color: #FFF;
    padding: 2px 6px;
    border-collapse: separate;
}
</style>

The tag is placed in the DOM, but it's ignored. So I'm either looking for a way to put CSS that is generated in the template, in the <head>. Or any other method for adding CSS other than inline on the element itself, since I can't use media queries that way. Just to be clear, the code above is put inside a loop, as I need the meta values from the post in order to generate the CSS.

Or is this just stupid?

Community
  • 1
  • 1
tobiasg
  • 983
  • 4
  • 17
  • 35

2 Answers2

2

Placing <style> tags within the <body> of your document is technically invalid, but in practice will work almost everywhere.

The problem I suspect you're running into is: the return value of uniqid() may begin with a number, and CSS identifiers cannot begin with numbers. So, if you generate an ID like "4b3403665fea6", your CSS might look okay, but it will be ignored.

You can fix this by passing a prefix to your call to uniqid(), like so:

$id = uniqid('id-');

...so that $id will be a value like "id-4b3403665fea6".

Sample demonstrating in-body <style>

<head>
<style>
  #id-4b3403665fea6 {
    background: blue;
  }
</style>
</head>

<body>
  <h1>Test</h1>
  <div id='id-4b3403665fea6'>Style me!</div>
  <style>
    #id-4b3403665fea6 {
        background: red!important;
        color: #FFF;
        padding: 2px 6px;
        border-collapse: separate;
    }
  </style>
</body>

Note that the <div> winds up with a red background, not blue like the <head> style specifies.

s3cur3
  • 2,749
  • 2
  • 27
  • 42
1

Hope this will help you.

<?php
$id = uniqid('cnt-');
?>

<style>
    #<?php echo $id; ?> {
        background: red!important;
        color: #FFF;
        padding: 2px 6px;
        border-collapse: separate;
    }
</style>
<div id="<?php echo $id; ?>">Test Content</div>
Karthik Sekar
  • 625
  • 4
  • 7