Search code examples
phphtmlcssmedia-queriesattr

CSS attr() for integers: What is a good way to solve this?


PHP Template:

  <div 
class="el" 
data-spacetop="<?php echo $spacetop; ?>" 
data-spaceleft="<?php echo $spaceleft; ?>" 
data-spacetopmobile="<?php echo $spacetopmobile; ?>" 
data-spaceleftmobile="<?php echo $spaceleftmobile; ?>"></div>

HTML:

<div class="el" data-spacetop="228" data-spaceleft="876" data-spacetopmobile="90" data-spaceleftmobile="20"></div>

CSS:

 .el {
        padding-top: attr(data-spacetop) px;
        padding-left: attr(data-spaceleft) px;
    }

@media screen and (max-width:600px) {
    .el {
        padding-top: attr(data-spacetopmobile) px;
        padding-left: attr(data-spaceleftmobile) px;
    }
}

If this would work it would be just wonderful. Unfortunatly it does not, although a W3C draft has been around for a long time now (https://caniuse.com/#feat=css3-attr).

How would you solve this problem? Unfortunatly inline media queries are not supported, too.


Solution

  • If you need to support modern browser you could use the new shining CSS custom properties instead of data-attributes and attr()

    Codepen demo


    Markup

    <div class="el" 
    style="
       --spacetop:40px;
       --spaceleft:20px;
       --spacetopmobile:10px;
       --spaceleftmobile:5px
    "></div>
    

    CSS

    .el {
      border: 1px #bc9 dashed;
      padding-top: var(--spacetop);
      padding-left: var(--spaceleft);
    }
    
    @media screen and (max-width:600px) {
      .el {
        padding-top: var(--spacetopmobile);
        padding-left: var(--spaceleftmobile);
      }
    }