2017-01-17 14 views
0

次のコードは、すべてに灰色のボックスを適用します<divs>特定のクラスに適用したいdivsどこかのIDを追加する必要がありますか?特定のdivへのクラス

<!DOCTYPE html> 
<html> 
<head> 
<style> 
div { 
    width: 320px; 
    padding: 10px; 
    border: 5px solid gray; 
    margin: 0; 
} 
</style> 
</head> 
<body> 

<h2>Calculate the total width:</h2> 

<img src="klematis4_big.jpg" width="350" height="263" alt="Klematis"> 
<div>The picture above is 350px wide. The total width of this element is also 350px.</div> 

</body> 
</html> 

enter image description here

+2

使用 'div.someClass'の代わりに、あなたのCSSでちょうど' div'。マークアップで 'style = 'someClass''を追加してスタイルを適用します。 – Chris

+0

IDは1つの要素に対してのみ使用できます。複数の要素に同じCSSを適用する場合は、代わりにクラスを使用します。 – j08691

答えて

2

ID(#idname)、またはより良いまだ、再利用可能なクラス(.classname)は、この要素をスタイリングのために適切であろう。

.caption { 
 
    width: 320px; 
 
    padding: 10px; 
 
    border: 5px solid gray; 
 
    margin: 0; 
 
}
<h2>Calculate the total width:</h2> 
 

 
<img src="http://placehold.it/350x263" width="350" height="263" alt="Klematis"> 
 
<div class="caption">The picture above is 350px wide. The total width of this element is also 350px.</div>

0

また、これを試すことができます。

CSS

.newStyle { 
    width: 320px; 
    padding: 10px; 
    border: 5px solid gray; 
    margin: 0; 
} 

HTML

<h2>Calculate the total width:</h2> 

<img src="klematis4_big.jpg" width="350" height="263" alt="Klematis"> 
<div id="dvText">The picture above is 350px wide. The total width of this element is also 350px.</div> 

JAVA SCRIPT

function addClass(el, className) { 
    var classes = el.className.match(/\S+/g) || []; 

    if (!hasClass(el, className)) { 
    classes.push(className); 
    } 
    el.className = classes.join(' '); 
} 

function hasClass(el, className) { 
    var re = new RegExp('(^|\\s+)' + className + '(\\s+|$)'); 
    return re.test(el.className); 
} 

addClass(document.getElementById('dvText'), 'newStyle') 
2
<!DOCTYPE html> 
<html> 
    <head> 
     <style> 
      greyBox { 
       width: 320px; 
       padding: 10px; 
       border: 5px solid gray; 
       margin: 0; 
      } 
     </style> 
    </head> 
    <body> 

    <h2>Calculate the total width:</h2> 

    <img src="klematis4_big.jpg" width="350" height="263" alt="Klematis"> 
    <div class = "greyBox" >The picture above is 350px wide. The total width of this element is also 350px.</div> 

    </body> 
</html> 
関連する問題