Joe
Joe

Reputation: 1

Vary css element width dynamically

I have the following shortcodes in a page or post:

[custom_width width='500' color='red']

[custom_width width='600' color='blue']

The shortcode function is to display 2 buttons with their respective width. The problem is that the buttons are displayed the same width using the last width of 600.

The function:

<?php
    function xyz ($attr) {
        $xyzwidth = $attr['width'];
        $xyzcolor = $attr['color'];
        my_style($xyzcolor);
?>

    <style type="text/css">
        .mystyle {
            width: <?php echo $xyzwidth; ?>px;
        }
    </style>

    <div class="mystyle">
        My Text
    </div>

<?php } ?>

note: the rest of the css is in its own .css file

function  my_style($xyzcolor) {
    switch ($xyzcolor) {
        case 'red': my_red();
            break;

        case 'blue': my_blue();
            break;
    }

<?php function my_red() { ?>
   <style type="text/css">
    .mystyle {
        ............
    }
    .mystyle: hover {
        ............
    }
    .mystyle a {
        ............
    }
    .mystyle a:hover {
        ............
    }
    </style>

<?php } ?>

Upvotes: 0

Views: 171

Answers (2)

user1823761
user1823761

Reputation:

Define your blue and red CSS in general. Not in your loop every time. Something like this:

<style type="text/css">
    // red
    .mystyle.red {
        ............
    }
    .mystyle.red:hover {
        ............
    }
    .mystyle.red a {
        ............
    }
    .mystyle.red a:hover {
        ............
    }

    // blue
    .mystyle.blue {
        ............
    }
    .mystyle.blue:hover {
        ............
    }
    .mystyle.blue a {
        ............
    }
    .mystyle.blue a:hover {
        ............
    }
</style>

And in your xyz function, give your div the desired class, and set the width of div internal:

<?php
    function xyz ($attr) {
        $xyzwidth = $attr['width'];
        $xyzcolor = $attr['color'];
        my_style($xyzcolor);
?>

    <div class="mystyle <?php echo $xyzcolor; ?>" style="width: <?php echo $xyzwidth; ?>px;">
        My Text
    </div>

<?php } ?>

Upvotes: 0

Paul Roub
Paul Roub

Reputation: 36458

If you're using the same class (mystyle) on both buttons, the last width defined on that class will apply to both elements.

For your purposes, you're probably better off with:

<?php
    function xyz ($attr) {
        $xyzwidth = $attr['width'];
?>

  <div style="width: <?php echo $xyzwidth; ?>px">
      My Text
  </div>

<?php
    }
?>

Upvotes: 2

Related Questions