When it comes to achieving this task, Mr Lister's solution is effective, but I personally prefer not using negative margins. Therefore, I wanted to propose a couple of alternative methods.
Pure CSS Approach (compatible with all browsers):
In the following example, I have enclosed non-<a>
contents within a span element inside each <li>
. The height for each <li>
is calculated using the calc function.
A CSS variable is also utilized here for easy adjustment of padding values in one place, which can be omitted if necessary.
:root {
--li-padding: 1em;
}
li {
height: calc(100% + (var(--li-padding) * 2));
line-height: calc(100% + (var(--li-padding) * 2));
background: tomato;
}
li>* {
padding: 0 var(--li-padding);
}
li a {
display: inline-block;
background: rgba(255, 255, 255, 0.6);
}
<ul>
<li><a href="#">Line 1</a></li>
<li><span>Line 2</span></li>
<li><a href="#">Line 3</a></li>
</ul>
Pure CSS Approach (currently unsupported by any browser, yet):
This method conforms to a proposed standard for CSS Level 4, though it is not implemented in any browser at present. However, it's worth mentioning for future reference.
Mozilla Documentation
li:not(::has(> a)) {
padding: 1em;
}
li>a {
padding: 1em;
}
<ul>
<li><a href="#">Line 1</a></li>
<li>Line 2</li>
<li><a href="#">Line 3</a></li>
</ul>
Utilizing JavaScript:
With Javascript, we can scan through all <li>
elements and apply specific actions based on their content. Here's a quick example demonstrating this concept (colors are used to indicate where <a>
tags start).
let liSelector = document.querySelectorAll('li');
for (let i = 0; i < liSelector.length; i++) {
let str = liSelector[i].innerHTML;
if (str.includes("</a>")) {
liSelector[i].querySelector('a').style.padding = "1em";
liSelector[i].querySelector('a').style.display = "inline-block";
} else {
liSelector[i].style.padding = "1em";
}
}
li {
background: tomato;
}
li a {
background: rgba(255, 255, 255, 0.6);
}
<ul>
<li><a href="#">Line 1</a></li>
<li>Line 2</li>
<li><a href="#">Line 3</a></li>
</ul>
Conclusion:
While Mr Lister's solution should suffice, exploring multiple options can enhance problem-solving skills and prepare for future challenges. I trust you will find this information beneficial 🙂