I have the following HTML, and I want each pair of dt
and dd
elements to be displayed in a single column, resulting in two columns per row. However, when using CSS Grid, it treats each dt
and dd
as separate columns.
Here’s the HTML:
<dl>
<dt>Term 1</dt>
<dd>Definition 1</dd>
<dt>Term 2</dt>
<dd>Definition 2</dd>
<dt>Term 3</dt>
<dd>Definition 3</dd>
<dt>Term 4</dt>
<dd>Definition 4</dd>
</dl>
My goal is to achieve this layout:
Term 1: Definition 1 | Term 2: Definition 2
Term 3: Definition 3 | Term 4: Definition 4
I cannot modify the HTML structure. I tried the following CSS, but it didn’t work as expected:
/* First attempt */
dl {
display:grid;
grid-template-areas: "
mm bb
";
grid-template-columns: 1fr 1fr;
}
dt, dd {grid-area: bb;}
dt:nth-of-type(2n) {
background:red;
grid-area: mm;
}
dt:nth-of-type(2n) + dd {
background:red; grid-area: mm;
}
/*dt:has(+ dd):nth-child(even), dt + dd {
border:1px solid blue;
}*/
And here’s another attempt that is closer to what I want but still not right:
dl {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20px;
}
dt, dd {
margin: 0;
}
dt:nth-of-type(odd),
dd:nth-of-type(odd) {
grid-column: 1;
}
dt:nth-of-type(even),
dd:nth-of-type(even) {
grid-column: 2;
}
dt {
font-weight: bold;
}
dd {
/* margin-left: 20px;*/
}
What am I doing wrong, and how can I fix this to get the desired layout with each dt
and dd
pair in a single column?
CodePen Example:
https://codepen.io/amit-cohen-the-selector/pen/jOoMGbV?editors=1100
Jack Sud is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.