Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there a way to modify property of css div in html

Tags:

html

css

class

I am kind of new to css and html coming form Actionscirpt.. I was wonder if there is a better way to do this.

I created an external css with following div.

 #myDiv{
position:absolute;
top:200px;
left:200px;  
width:200px;
height:200px;
}

and in html I want to use the same div for 3 different things with different value/property.

<div id="myDiv">The top and left needs to be 150px</div>
<div id="myDiv">The top and left needs to be 200px</div>
<div id="myDiv"> The top and left needs to be 300px</div>

Is there a simple way to do it without creating 3 divs in css...

like image 661
rex Avatar asked Feb 26 '23 05:02

rex


2 Answers

first of all, ID's are unique elements and you should only have 1 per page.

To apply the same style to multiple elements, you should use a class.

<div class="name-of-my-common-style">

And then from css, use a dot (.) instead of a hash (#) to define the style for that class. i.e.

.name-of-my-common-style {
    position:absolute;
    top:200px;
    left:200px;  
    width:200px;
    height:200px;
}

To override any styles, you can use inline CSS

<div class="name-of-my-common-style" style="width: 150px"> ... </div>

This will pick up the original styles from name-of-my-common-style but override the width due to the inline width setting of 150px.

Another approach is to create a separate class for each width declaration and apply it to the element. i.e.

.name-of-my-common-style { ..default styles here..}
.width-150 {width: 150px;}
.width-200 {width: 200px;}

And so forth...

Then you can use it like this.

<div class="name-of-my-common-style width-150">I'm 150px wide</div>

Hope this helps.

like image 113
Marko Avatar answered Mar 08 '23 15:03

Marko


.divvy { 
    /* common attributes go here */
    position: absolute;
    width: 200px;
    height: 200px;
}

/* specific (and unique attributes, since these are 'ids') here */
#d1 { top: 150px; left: 150px; }
#d2 { top: 200px; left: 200px; }
#d3 { top: 300px; left: 300px; }

In your HTML:

<div class="divvy" id="d1">The top and left needs to be 150px</div>
<div class="divvy" id="d2">The top and left needs to be 200px</div>
<div class="divvy" id="d3">The top and left needs to be 300px</div>
like image 33
miku Avatar answered Mar 08 '23 16:03

miku