csslist-definition

DL Tag - Vertical align text in DT Tag, color background and have same height as DD Tag


Given the following html & CSS:

dl.table-display {
  float: left;
  width: 520px;
  margin: 1em 0;
  padding: 0;
  border-bottom: 1px solid #999;
}

.table-display dt {
  clear: left;
  float: left;
  width: 200px;
  margin: 0;
  padding: 5px;
  border-top: 1px solid #999;
  font-weight: bold;
  background-color: #cccccc;
}

.table-display dd {
  float: left;
  width: 300px;
  margin: 0;
  padding: 5px;
  border-top: 1px solid #999;
}
<dl class="table-display">
  <dt>Key 1</dt>
  <dd>Value 1</dd>
  <dt>Key 2</dt>
  <dd>Value 2<br/>With line breaks<br/>and line breaks</dd>
</dl>

I am trying to center the text in the DT & DD tags and have the DT tag background color cover 100% of the longer DD tag. Create a .html file with the above code to see how it looks now. I did have this as a table but I am forced to use the DL markup now. Any help would be appreciated. Thanks!


Solution

  • setting a height for your dt elements will 'stretch' the background, and so long as this height is >= the height of the contained dd's, then it will look as you want.

    dt{height:100px;}
    

    providing text-align:center on the dl tag will center your text.

    dl{text-align:center;}
    

    The hard part is then trying to vertically align the text to the middle. An option for this is to contain the text in an absolute positioned div.. but is a bit messy.

    <dt><div>Key 1</div></dt>
    
    dt{position:relative;height:100px;}
    dt div{position:absolute;bottom:50px;}
    

    check here for other options/solutions Vertical Align text in a Label

    hope this helps..