Don W.
Don W.

Reputation: 560

vertically align a div and a span using css

please see the jsfiddle project here . How to horizontally align the box and the label?

.box {
  display: inline-block;
  height: 20px;
  width: 30px;
  border: 1px solid;
}

.legend {
  horizontal-align: middle;
}
<div class="legend">
  <div class="box" style="background-color: red;">
  </div>
  <span>Alabama</span>
</div>

Upvotes: 0

Views: 73

Answers (4)

j08691
j08691

Reputation: 207901

Setting the vertical-align property on the .box div would seem to make the most sense and cause the least issues.

.box {
  display: inline-block;
  height: 20px;
  width: 30px;
  border: 1px solid;
  vertical-align: middle;
}
<div class="legend">
  <div class="box" style="background-color: red;">
  </div>
  <span>Alabama</span>
</div>

Upvotes: 1

Seth Warburton
Seth Warburton

Reputation: 2413

I assume you mean vertically align? If you are simply trying to align, vertically, two div of unequal height then display: inline-block is the simplest and most effective method. You almost had it with your code, but float breaks it. Don't use float!

.box {
  background-color: red;
  border: 1px solid;
  height: 20px;
  width: 30px;
}

.box,
.legend {
  display: inline-block;
  vertical-align: middle;
}
  <div class="box"></div>
  <div class="legend">Alabama</div>

enter link description here

Upvotes: 1

Narutkowski
Narutkowski

Reputation: 175

Why not use flexbox?

If you're trying to vertically align the two items within .legend then just apply these styles:

.legend {
  display: flex;
  align-items: center;
}

Keep in mind you will need to apply prefixes for cross-browser compatibility.

Upvotes: 0

Christopher Marshall
Christopher Marshall

Reputation: 10736

You can float the box instead of displaying it inline. There's a couple different ways to align these.

https://jsfiddle.net/cckxkvov/5/

.box {
  float: left;
  height: 20px;
  width: 30px;
  border: 1px solid;
}

.legend {
  horizontal-align: middle;
}

span {
  display: inline-block;
  line-height: 20px; 
}

Upvotes: 0

Related Questions