2

Say I have some css like:

.modal-350 {
    width: 350px;
}
.modal-400 {
    width: 400px;
}
.modal-500 {
    width: 500px;
}

etc. Using only CSS is it possible to set the width (or other property) just from the class name?

I know in javascript this is easy and also I could just use:

.modal-auto {
    display: inline-block;
    width:auto;
}

It's not production code, I'm just curious.

4
  • 4
    No, that's not how CSS works. The closest you can get is to use attr() to reference other HTML attributes, and that's not well-supported. Commented Oct 27, 2017 at 13:31
  • I didn't think so, but still it was worth knowing for sure! Commented Oct 27, 2017 at 13:33
  • That may work for a single element or a section, But when you have to create a whole website that will make everything complicated. So be wise while you select class names. Commented Oct 27, 2017 at 13:35
  • It was just example code for the question. Commented Oct 27, 2017 at 13:36

1 Answer 1

1

No. Even though we can use variables in CSS, we can only do so in property values and not in selector names. So something like this will not work:

.modal-$size {
    width: ${size}px;
}

You can, however, use a CSS preprocessor such as LESS or SASS, and generate such rules automagically, given the requested sizes.

A SASS example:

$modal-sizes: 50 100 200 500;

%modal-default {
  border-radius: 50%;
  color: red;
  background: green;
  border-color: blue;
}

@mixin modals {
  @each $size in $modal-sizes {
      .modal-#{$size} {
        @extend %modal-default;
        width: #{$size}px;
      }
  }
}

@include modals;

This will compile as:

.modal-50, .modal-100, .modal-200, .modal-500 {
  border-radius: 50%;
  color: red;
  background: green;
  border-color: blue;
}

.modal-50 {
  width: 50px;
}

.modal-100 {
  width: 100px;
}

.modal-200 {
  width: 200px;
}

.modal-500 {
  width: 500px;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.