Kyle Dunne
Kyle Dunne

Reputation: 231

Group multiple css classes to another class

My page has specific styling for whatever city or state the person is from. So if they were from New Jersey the background would be red for example. To do this right now I'm doing something like:

HTML/PHP

<div class="<?php echo $row["location"]; ?>">
  <div class="Container">
    <div class="Top-Bar">Name</div>
    <div class="Bottom-Bar">Location</div>
  </div>
</div>

CSS

.New.Jersey .Top-Bar, 
.New.Jersey .Bottom-Bar {
  background-color: red;
}

.Pennsylvania .Top-Bar, 
.Pennsylvania .Bottom-Bar {
  background-color: blue;
}

When I want to add a new element to the page that is colored I have to go to every line and physically add something like .Pennsylvania .Middle-Bar for every location I have.

Is there a better way to do this? I know I can do some database with color codes and do the styles that way but I'd prefer to have as much on the stylesheet for performance.

Upvotes: 3

Views: 1421

Answers (3)

Mehow
Mehow

Reputation: 25

With scss/sass u can achieve nested classes which will help you reach your goal.

$pallete: ( white: #fff, black: #000, red: #d43862, green: #00a665, orange: #ff9100, blue: #008acd, ghost: rgb(129, 129, 129) );

@each $palleteColor, $color in $pallete {
    .col-#{$palleteColor} {
        color: $color;
        &-darken {
            color: darken($color, 20% );
        }
    }
    .bg-col-#{$palleteColor} {
        background-color: $color;
        &-darken {
            background-color: darken($color, 20% );
        }
    }
}

and u can use your class as .bg-col-white, .col-black, .col-black-darken

If you want to compile this, just install npm and then use compiler for sass

'use strict';

var gulp = require('gulp');
var sass = require('gulp-sass');

gulp.task('sass', function () {
  return gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

here is complete guide for gulp

And if you would like to use webpack

var webpack = require('webpack'),
    autoprefixer = require('autoprefixer'),
    ExtractTextPlugin = require('extract-text-webpack-plugin'),
    path = require('path');

var SRC_DIR = path.resolve(__dirname, 'src');
var DIST_DIR = path.resolve(__dirname, 'dist');
var config = [{
    name: 'styles',
    context: __dirname,
    entry: {
        styles: SRC_DIR + "/scss/styles.scss",
        framework: SRC_DIR + "/scss/bulkenny/index.scss"
    },
    devtool: debug ? "inline-sourcemap" : null,
    exclude: '/node_modules/',
    output: {
        path: DIST_DIR + '/css',
        filename: '[name].min.css'
    },
    module: {
        loaders: [
            { test: /\.(scss|sass)$/, loader: ExtractTextPlugin.extract('style-loader', ['css-loader', 'postcss-loader', 'sass-loader']) }
        ]
    },
    postcss: function(webpack) {
        plugins: [autoprefixer,
            require('postcss-combine-duplicated-selectors'),
            require('css-mqpacker'),
            require('postcss-discard-unused')
        ]
    },
    plugins: [
        new ExtractTextPlugin('[name].min.css')
    ]
}];

module.exports = config;

And then, with your php do something like this (ofc not tested, but u can get how it should looks like)

<?
function countryColor($countryName){
$colors = array('Minesota'=> 'red', 'Sosnowiec'=>'pink');
return $colors[$countryName];
}

$users = array(
   array("username"=> "Adam", "location"=>"Minesota"),
   array("username"=> "Paul", "location"=>"Sosnowiec")
);


foreach ($users as $index=>$user){

?>
<div class="bg-col-<?php echo countryColor($user['location']); ?>">
  <div class="Container">
    <div class="Top-Bar">Name</div>
    <div class="Bottom-Bar">Location</div>
  </div>
</div>
<?php
}
?>

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 115045

I'n this case I cannot recommend using a CSS Pre-processor enough. There are a few, SASS, LESS, Stylus and others.

The make writing long CSS much easier and quicker although you should be aware that the don't necessarily reduce the amount of CSS that is output.

They have a wide variety of clever functions, one of which can help you here.

In SASS they are called Maps.

So this:

$states-bg: (
  pa: red,
  nj: blue,
  ny: green,
  ca: orange,
  tx: rebeccapurple
);


@each $state, $bg-color in $states-bg {
  .#{$state} .state-bg-color {
    background: $bg-color;
    }
}

actually outputs this:

.pa .state-bg-color {
  background: red;
}

.nj .state-bg-color {
  background: blue;
}

.ny .state-bg-color {
  background: green;
}

.ca .state-bg-color {
  background: orange;
}

.tx .state-bg-color {
  background: rebeccapurple;
}

We define our map by giving it a name $state-bg and then each "state" item in the map has a corresponding color value.

If we use a single class-name for our background color this gets spat out automagically.

One list to maintain that can be extended as required.

You can play with this here: Sassmeister

Upvotes: 0

Alohci
Alohci

Reputation: 82986

Why not write

<div class="<?php echo $row["location"]; ?>">
  <div class="Container">
    <div class="Top Bar">Name</div>
    <div class="Bottom Bar">Location</div>
  </div>
</div>

And

.New.Jersey .Bar
  background-color: red;
}

.Pennsylvania .Bar
  background-color: blue;
}

Then if you want another element, you can write, say

<div class="Middle Bar">Population</div>

And the color styling will be picked up automatically.

If you want some other styling (say font-weight) specific to the middle bar instead of writing

.Pennsylvania .Middle-Bar
  font-weight: bold;
}

You'd write

.Pennsylvania .Middle.Bar
  font-weight: bold;
}

Upvotes: 3

Related Questions