Home > Software engineering >  need short css , so that don't have to write again and again the same css
need short css , so that don't have to write again and again the same css

Time:12-31

ok so , the question is this , I have 2 div in my html file

<div id="box1></div>
<div id="box2></div>

now, these 2 boxes have same css like this

#box1{
background:#FFFFFF;
height:59px;
width:59px;
position:absolute;
top:7rem;
left:8.3rem;
 }

#box2{
background:#FFFFFF;
height:59px;
width:59px;
 position:absolute;
top:7rem;
left:12.3rem;
}

but , if you see the code i don't want to write all the same property as i want only to change the position of the second block but want to have same property as box1 . is there any way to short these css or any trick please help!!

CodePudding user response:

You can collect all the same css together and then overwrite changing bits:

#box1, #box2 {
  background:#FFFFFF;
  height:59px;
  width:59px;
  position:absolute;
  top:7rem;
  left:8.3rem;
}

#box2{
  left:12.3rem;
}

CodePudding user response:

#box1, #box2 {
  background:#FFFFFF;
  height:59px;
  width:59px;
  position:absolute;
  top:7rem;
}

#box1 {
  left:8.3rem;
}

#box2 {
  left:12.3rem;
}
<div id="box1"></div>
<div id="box2"></div>

CodePudding user response:

There are many ways in which you can achieve this

  1. Overrite Specific parts - You can write the common CSS properties in one block and the properties which differentiate the id selectors can be written in different blocks separately.
#box1, #box2 {
    background:#FFFFFF;
    height:59px;
    width:59px;
    position:absolute;
    top:7rem;
    left:8.3rem;
}
#box2{
    left:12.3rem;
}
  1. Use LESS or SaaS to further enhance CSS capabilities. These tools include functions similar to the inheritance(Though it's not inheritance) which lets you have a base class and then derive other properties for different ids.

CodePudding user response:

Start with fixing your HTML. There are " missing. It's a good practice to use reusable classes for styling instead of IDs.

<div id="box1" ></div>
<div id="box2" ></div>

Now put common attributes in a class.

.box {
  background: #FFFFFF;
  height: 59px;
  width: 59px;
  position: absolute;
  top: 7rem;
}

#box1 {
  left: 8.3rem;
}

#box2 {
  left: 12.3rem;
}

You have good intuition if you ask "how not to repeat myself" in this situation. Here's a lesson that can help you understand how and why I recommend this solution: https://www.freecodecamp.org/learn/responsive-web-design/basic-css/style-multiple-elements-with-a-css-class

  • Related