choose the <li> element with no <a> tag

Hello there,

I am looking for a way to keep the padding consistent in <li> elements, but have it applied to the <a> tag instead when it's a link (to create a larger selection area).

li a {
  padding: 1rem;
}

li:not(a) {
  padding: 1rem;
}
<ul>
  <li><a href='#'>Text</a></li>
  <li>Text</li>
  <li><a href='#'>Text</a></li>
</ul>
  • I want the padding to be on the <a> element if it exists, rather than the <li>
  • If there is no <a>, then the padding should be applied to the <li>

Answer №1

To achieve the desired effect, apply negative margins to the a element so that its padding aligns with the li element's padding.

li {
  padding: 1rem;
}

li a {
  margin: -1rem;
  padding: 1rem;
}
<ul>
  <li><a href='#'>Text</a></li>
  <li>Text</li>
  <li><a href='#'>Text</a></li>
</ul>

Answer №2

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 🙂

Answer №3

Here is a jQuery example:

$('li').each(function() {
    if($(this).find('a').length) {
       $(this).addClass('extrapadding');
    }
});
.extrapadding a {
  padding: 1rem;
}

li:not(.extrapadding) {
  padding: 1rem;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li><a href='#'>Text</a></li>
<li>Text</li>
<li><a href='#'>Text</a></li>
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a stripped box shadow with just HTML and CSS - a simple guide

Hey there! I'm trying to create a navbar button with a cool stripped box shadow effect when hovered, similar to what you see in this image link. I attempted to achieve this using CSS box-shadow and linear gradient, but unfortunately it didn't qui ...

Creating a sticky footer using Vue.js for both mobile and desktop display views

Looking for a solution to create a sticky footer that works on both desktop and mobile views without overlapping the main content? The current code either overlaps or doesn't stick to the bottom. Seeking a responsive approach. App.vue: <template& ...

Tips for Utilizing CSS Overflow: Hidden to Prevent the Parent Container from Expanding

I have a fixed width column and a fluid column. In the fluid column, I want to display a string with nowrap so that it does not overflow the container. Here is an illustration of how I want the text to appear: --------------------------------------------- ...

What is the best way to target elements that have the contentEditable attribute set to true using CSS?

Can someone help me style table cells that have contentEditable set to "true"? I've tried various CSS selectors like td[contenteditable], td[contenteditable=true], and td[contenteditable="true"], but none seem to work. Is there a specific selector for ...

Change the color of specific elements in an SVG using React

Can I change the dynamic primary color from ReactJS to a specific class in an SVG file? If yes, how can it be done? Error.svg <!-- Generator: Adobe Illustrator 26.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1&qu ...

Trouble with bringing in the solana/web3.js library

After successfully importing the solana/web3.js package and running it within a NodeJS file, everything was working fine. However, things took a turn when attempting to connect this file with basic HTML, resulting in an error being thrown. import { Tra ...

Stop horizontal scrolling when using connected lists in full-height columns with jQuery UI Sortable

I am in the process of developing a web application that features two full-height columns utilizing Flexbox in Bootstrap v4. Each column contains a sortable list that can be rearranged using jQuery UI Sortable. HTML: <div class="container-fluid h-100 ...

Avoid auto-scaling of div content

I need the .content within the main container .box to resize proportionally to match the width of the .box exactly, without being smaller. .box { width: 95%; background-color: red; padding: 20px; text-align: center; margin: 55px auto 40px; } . ...

Tips on positioning a dropdown item to the far right of the page

I need help moving the language switcher and its items to the right side of the page. I tried using ml-auto but it didn't work for me. Whenever I try to adjust the position with padding-left, all the items end up in the center of the page. Any suggest ...

Navigating through website links while working locally on a localhost server can

After exclusively working on live domains or subdomains in the past, I recently experienced the benefits of working on localhost. Utilizing a Wamp server on my Windows machine, I store my project in C:/wamp64/www/[project_name]. I have always used relativ ...

The flexbox container is not displaying properly

I have rows containing two flex divs each. One div displays an image, while the other has text. I'm puzzled as to why some divs display correctly while others have overflowing text. Refreshing the page resolves this issue, but it resurfaces if I clea ...

Issue with CakePdf unable to properly render CSS styling

I am having issues with the CakePdf Plugin (CakePdf.DomPdf) as it is not recognizing my stylesheet. Despite copying my /View/Layouts/default.ctp to /View/Layouts/pdf/default.ctp, the pdf file generated does not reflect the styling. Could this be due to t ...

Tips for creating a Google Chart using temperature and humidity data sourced from an XML file

Below is the XML file I am working with: <data> <temp>21</temp> <humidity>17</humidity> <analog>670</analog> <analog>908</analog> <analog>628</analog> <analog>909</analog> <L ...

Python // Regular Expressions // Categories

My attempt to retrieve specific text content from various HTML tags using BeautifulSoup (BS4) proved unsuccessful. The code snippet I used only managed to extract the first text item after the <td tag, leaving out the rest that I needed. My goal is to p ...

Ensure that the spacing between rows matches the spacing between columns

I am working on creating a 3x3 grid using Bootstrap. My goal is to have consistent spacing between the rows and columns. How can I achieve this effectively? ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Utilizing jquery's .find() method to tally up elements, while excluding any elements located inside a specific div

I am looking for a solution to tally specific child elements, excluding those housed within an element with a certain class. To count elements, I currently use $('.search-me').find('[class*=seI\\-]').length within a div conta ...

Tips for consistently showing the addition symbol in my search bar

I created a code snippet that showcases a search box with CSS animations and jQuery toggling functionality. One issue I encountered is ensuring that the plus icon remains visible at all times, whether the search box is expanded or contracted. How can I ac ...

Ways to adjust the visibility of a div element multiple times using javascript and css

I implemented a popup feature in my application: <div id="modal"></div> let modal = document.getElementById('modal') modal.innerHTML = ` <button class="close-button" onclick="close_modal()" ...

Maintain scroll position during ajax request

I am working on a single-page website that contains numerous containers. Each container's content is loaded dynamically via ajax, so they may not all be populated at the same time. These containers have variable heights set to auto. The website uti ...