1

The title is a bit confusing, so let me show you. Lets say I have the following inside CSS file:

#container_1 {
    width:50%;
    border:1px solid black;
    }

#container_2 {
    background-color:red;
    padding:5px;
}

If I want the container_2 to have 50% width and 1x border, same as the container_1, is there some way to define CSS of container_2 while including the CSS from container_1 without actually having to put in 50% width and 1x border for CSS of container_2?

Something like:

#container_2 {
    include:#container_1;
    background-color:red;
    padding:5px;
}

Thanks

Pioneerx01
  • 13
  • 4
  • @Dhaust I think it's not a duplicate of that because he is asking if he can define another style in another file with including other style from the other file. – Francis G Jun 04 '19 at 04:03

4 Answers4

1

In css we cannot inherit properties of one class to another directly, however to simplify this we can write the above code like :

#container_1,#container_2 {
    width:50%;
    border:1px solid black;
    }

#container_2 {
    background-color:red;
    padding:5px;
}

This way #container_2 will have all the properties of #container_1 apart from its unique properties.

OR

We can use Sass for doing the same, Sass has a feature called @mixin where we can achieve this.

For e.g.

@mixin reset-list {
  margin: 0;
  padding: 0;
  list-style: none;
}

@mixin horizontal-list {
  @include reset-list;

  li {
    display: inline-block;
    margin: {
      left: -2px;
      right: 2em;
    }
  }
}

For more details you can visit https://sass-lang.com/documentation/at-rules/mixin

Nikhil
  • 11
  • 3
0

add comma to set the container_2 same style with container_1

#container_1,#container_2 {
    width:50%;
    border:1px solid black;
    }

#container_2 {
    background-color:red;
    padding:5px;
}
rrsantos
  • 404
  • 4
  • 14
0

You could write it like this:

#container_1, 
#container_2 {
    /* Shared Styles */
    width:50%;
    border:1px solid black;
}

#container_2 {
    background-color:red;
    padding:5px;
}

Otherwise you could make one class that all containers share in HTML.

#container_base {
    /* Shared Styles */
}
#container_2 {
    background-color:red;
    padding:5px;
}    

<div class="container_base container_2"></div>
mullac
  • 693
  • 6
  • 17
0

You can do like something like this.

#container is your command class so you need to take about their property.

#container_2 {
    background-color:red;
    padding:5px;
}

#container_1, #container2 {
    width:50%;
    border:1px solid black;
}

In the above code you get the actual output as you want.

Ravindra Bhanderi
  • 2,478
  • 4
  • 17
  • 29