我对css和html有点新的形式来自Actionscirpt ..我很想知道是否有更好的方法来做到这一点。
我使用以下div创建了一个外部css。
#myDiv{
position:absolute;
top:200px;
left:200px;
width:200px;
height:200px;
}
并且在html中我想对具有不同值/属性的3个不同的东西使用相同的div。
<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>
有没有一种简单的方法可以在css中创建3个div ...
答案 0 :(得分:4)
首先,ID是唯一的元素,每页只能有1个。
要将相同的样式应用于多个元素,您应该使用一个类。
<div class="name-of-my-common-style">
然后从css开始,使用点(。)而不是哈希(#)来定义该类的样式。即。
.name-of-my-common-style {
position:absolute;
top:200px;
left:200px;
width:200px;
height:200px;
}
要覆盖任何样式,您可以使用内嵌CSS
<div class="name-of-my-common-style" style="width: 150px"> ... </div>
这将从name-of-my-common-style
中选取原始样式,但由于width
的内联150px
设置而覆盖宽度。
另一种方法是为每个宽度声明创建一个单独的类,并将其应用于元素。的即强>
.name-of-my-common-style { ..default styles here..}
.width-150 {width: 150px;}
.width-200 {width: 200px;}
等等......
然后你可以像这样使用它。
<div class="name-of-my-common-style width-150">I'm 150px wide</div>
希望这会有所帮助。
答案 1 :(得分:2)
.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; }
在您的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>
答案 2 :(得分:1)
首先,您永远不应该有多个具有相同ID的元素。 ID应该是唯一的。
如果内联样式没有意义,这是实现目标的最直接的方法:
.myDiv{ position:absolute; width:200px; height:200px; }
#myDiv1 { top: 150px; left: 150px; }
#myDiv2 { top: 200px; left: 200px; }
#myDiv3 { top: 300px; left: 300px; }
然后在HTML中:
<div id="myDiv1" class="myDiv">The top and left needs to be 150px</div>
<div id="myDiv2" class="myDiv">The top and left needs to be 200px</div>
<div id="myDiv3" class="myDiv">The top and left needs to be 300px</div>
答案 3 :(得分:1)
首先,id应该只用在一个元素上。你真的想使用'class'而不是'id'(而你的css将是 .myDiv 而不是 #myDiv
在css中不创建3个div的唯一方法是在div标签中应用其他样式属性,您需要覆盖css中的样式。
例如:
<div class="myDiv" style="top: 150px; left: 150px;"> ... </div>
<div class="myDiv"> this just uses the default style from the css </div>
<div class="myDiv" style="top: 300px; left: 300px;"> ... </div>
答案 4 :(得分:0)
您可以使用:<div id="myDiv" style="top: 150px; left: 150px;">
更改的属性将被覆盖,但其余的将保留为您的CSS文件。
CSS优先级是这样给出的(从最高到最低):内联 - &gt; <head>
代码中的CSS - &gt;外部CSS文件中的定义。
但是,正如NullUserException所述,理想情况下每个div应该是唯一的。