sramij
sramij

Reputation: 4925

How to apply CSS style when ID is taken?

I am a newbie at HTML coding, and I have the following HTML element:

<div id="map_canvas" style="width: 500px; height: 370px; border: 1px solid #ccc; float: left"></div>

I want to apply for it a "left" CSS style. I've been doing that for other items using:

<div id="left" >
    <input type=button ....
</div>

However, as you can see, map_canvas is already the id for my element, so how can I apply the CSS element with id left for it?

Upvotes: 1

Views: 266

Answers (2)

Luis Perez
Luis Perez

Reputation: 28130

All id's must be unique. Use a hash in your CSS to apply a style to a unique element by id:

#unique { font-size: 200px; }

<div id="unique">My Unique one of a kind element</div>

When you want to apply a style to multiple elements use classes:

.BoldRed { font-weight: bold; color: red; }

<div class="BoldRed">This is important</div>
<div class="BoldRed">So is this</div>

You can also combine classes:

.ReallyImportant { text-decoration: underline; }

<div class="BoldRed ReallyImportant">This is the most important</div>

Upvotes: 1

Jared Farrish
Jared Farrish

Reputation: 49238

#map_canvas {
    width: 500px;
    height: 370px;
    border: 1px solid #ccc;
}

.left {
    float: left;
    border: 1px solid blue;
}

<div class="left">Not #map_canvas</div>
<div id="map_canvas" class="left">This is #map_canvas .left</div>

http://jsfiddle.net/94dwn/3/

Note that the width of an element govern's it's float to the next "line" if the "next" element isn't "cleared", so if an element is narrower on display than the previously floated element, it could go to the right/left of that element. In that case, you should use clear.

<div class="left">Not #map_canvas</div>
<div id="map_canvas" class="left">This is #map_canvas .left</div>
<div class="cleared">Clear</div>

#map_canvas {
    width: 500px;
    height: 370px;
    border: 1px solid #ccc;
}
.left {
    float: left;
    border: 1px solid blue;
}
.cleared {
    clear: both;
    background: green;
    border: 1px solid blue;
    color: white;
}

http://jsfiddle.net/94dwn/4/

Upvotes: 7

Related Questions