Recently, I discovered the 30 Seconds of Code website, and their CSS examples are truly impressive! I was particularly captivated by their "floating section headers" using definition lists. This elegantly demonstrates the power and versatility of <dl></dl>
, <dt></dt>
, and <dd></dd>
elements.
Consider this simple HTML:
<div> <dl> <dt>A</dt> <dd>Algeria</dd> <dd>Angola</dd> <dt>B</dt> <dd>Benin</dd> <dd>Botswana</dd> <dd>Burkina Faso</dd> <dd>Burundi</dd> <dt>C</dt> <dd>Cabo Verde</dd> <dd>Cameroon</dd> <dd>Central African Republic</dd> <dd>Chad</dd> <dd>Comoros</dd> <dd>Congo, Democratic Republic of the</dd> <dd>Congo, Republic of the</dd> <dd>Cote d'Ivoire</dd> <dt>D</dt> <dd>Djibouti</dd> <dt>E</dt> <dd>Egypt</dd> <dd>Equatorial Guinea</dd> <dd>Eritrea</dd> <dd>Eswatini (formerly Swaziland)</dd> <dd>Ethiopia</dd> </dl> </div>
Without any CSS, the browser's default rendering is straightforward. However, the inherent structure of <dt></dt>
and <dd></dd>
allows for clever styling. Notice how the <dt></dt>
elements naturally align to the left due to the default margin. This makes creating "sticky sections" remarkably easy:
dt { position: sticky; top: 0; background: white; display: inline-block; }
The elegance of this solution is striking. The core functionality is achieved with minimal CSS. Further styling is purely cosmetic enhancement.
The 30 Seconds of Code example employs CSS Grid for a more robust layout, but this concise CSS approach highlights how much can be accomplished with less. They also offer a variation where <dd></dd>
elements span the full width, providing another interesting design option.
The above is the detailed content of Sticky Definition Lists. For more information, please follow other related articles on the PHP Chinese website!