AlienHunter 67 AlienHunter 67 - 2 months ago 5
CSS Question

How to align text next to a "div" in HTML/CSS?

I have put an image map to my website with multiple colours, so I wanted to make a "div" block and next to it an explanation of what that colour represents on the map. But, when I try to do it, the text just goes under the "div", like so:



#dark_green {height: 40px;
width: 80px;
background-color: #009933; }

#light_green {height: 40px;
width: 80px;
background-color: #00ff00;
}

#dark_red {height: 40px;
width: 80px;
background-color: #ff0000;
}

#light_orange {height: 40px;
width: 80px;
background-color: #ff8c1a;
}

<div id="dark_green"></div> - Dark Green
<br>
<div id="light_green"></div> - Light Green
<br>
<div id="dark_red"></div> - Dark Red
<br>
<div id="light_orange"></div> - Light Orange





How can I make the text align next to each of the "divs"?

Answer

With the markup you gave us here, just make all the boxes displaying as an inline-block.

Notice: Just add the things, which make an element unique, to an id. All the rest, which is the same for multiple elements, should be in a class. Why? If you want to make the box - let's say - 20px wider, you will have to edit every box-id at the moment, with my improvement in your code, you just have to edit the class once and you're all done.

Edit: Wrap your explanations into an element, a <span> would be just fine here. Then you are able to apply styles to them (position, color, etc.).

.box {
    width: 80px;
    height: 40px;
    display: inline-block;
    vertical-align: middle;
}

.explanation {
    margin-left: 5px;
    vertical-align: middle;
}

#dark_green {
    background-color: #009933;
}

#light_green {
    background-color: #00ff00;
}

#dark_red {
    background-color: #ff0000;
}

#light_orange {
    background-color: #ff8c1a;
}
<div id="dark_green" class="box"></div><span class="explanation">- Dark Green</span>
<br>
<div id="light_green" class="box"></div><span class="explanation">- Light Green</span>
<br>
<div id="dark_red" class="box"></div><span class="explanation">- Dark Red</span>
<br>
<div id="light_orange" class="box"></div><span class="explanation">- Light Orange</span>

Comments