crazy novice
crazy novice

Reputation: 1817

Is it possible to combined common styles and remove repetition

Here is simplified version of html

<div id="id1"></div>
<div id="id2"></div>

Here is my CSS.

#id1 {
    display: -ms-flexbox;
    -ms-flex-direction: row;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

#id2 {
    display: -ms-flexbox;
    -ms-flex-direction: column;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

The only difference between two styles is the -ms-flex-direction been row vs column. All other 3 properties are same. Is there anyway of combining the two so that same code is not repeated?

Upvotes: 0

Views: 57

Answers (2)

Axel A. Garc&#237;a
Axel A. Garc&#237;a

Reputation: 683

In this case you can apply common styles to both div, then make the difference with your ID (Classes are better for this BTW)

div {
    display: -ms-flexbox;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

#id1 {
    -ms-flex-direction: row;
}

#id2 {
    -ms-flex-direction: column;
}

This is waaay better

HTML

<div class="flexbox row"></div>
<div class="flexbox column"></div>

CSS

.flexbox {
    display: -ms-flexbox;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

.flexbox.row{
    -ms-flex-direction: row;
}

.flexbox.column {
    -ms-flex-direction: column;
}

Upvotes: 1

Matthew R.
Matthew R.

Reputation: 4350

When properties are shared between elements you should use a class to target them. IDs should only be on a single element as a unique identifier. Here is how you would implement a class:

<div id="id1" class="same"></div>
<div id="id2" class="same"></div>

CSS:

.same {
    display: -ms-flexbox;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

#id1 {
    -ms-flex-direction: row;
}

#id2 {
    -ms-flex-direction: column;
}

You can also assign multiple classes to an element by using a space. So this:

<div id="id1" class="same different"></div>
<div id="id2" class="same not-different"></div>
<div id="id3" class="same not-different"></div>

CSS:

.same {
    display: -ms-flexbox;
    width: 100px;
    height: 200px;
    border: 1px solid;
}

.different {
    background: green;
}

.not-different {
    background: red;
}

#id1 {
    -ms-flex-direction: row;
}

#id2 {
    -ms-flex-direction: column;
}

This will allow you to target multiple items using class chaining.

Upvotes: 1

Related Questions