What is the best way to reverse a condition in CSS?

Here is my HTML/CSS code, I am relatively new to this field. Please let me know if I have overlooked anything.

.dropdown-menu>li>a {
  padding: 3px 5px;
}
<li>
  <a id="btn-other-1" href="#">
    <!–- I do not want apply css for this anchor tag because it has i inside –->
    <i class="fa fa-check" aria-hidden="true"></i>
    <span> Other stuff-1? </span>
  </a>
</li>
<li>
  <a id="btn-other-2" href="#">
    <span> Other stuff-2 </span>
  </a>
</li>

The issue I am facing is that the CSS code I provided applies to all anchor tags within <li>, but I want to exclude the ones with an <i> tag inside them.

How can I achieve this in CSS?

Answer №1

Unfortunately, CSS does not have the capability to select and style a parent element. To achieve this functionality, you would need to utilize either jQuery or JavaScript.

$('.dropdown-menu a i').parent().css('padding','0');

I trust this information proves useful to your needs.

Answer №2

It has been noted by kravisingh that there is currently no parent selector in CSS.

Even without altering your HTML structure, there is a workaround for the given example: you can add padding to the children of the link element. The great thing about your specific case is that you can easily differentiate between the children using just CSS.

I utilized the :only-child pseudo-class to target a span element which has no siblings (meaning there are no preceding or following sibling elements), as illustrated below.
Additionally, CSS offers these selectors at your disposal:

  • :first-child (if the span matches, it implies there is no preceding i element)
  • :last-child
  • + the adjacent sibling combinator (i + a { /* */ } targets an a immediately following an i?)
  • ~ the general sibling combinator (i ~ a { /* */ } selects an a that comes after an i, possibly with other elements in between?)
  • and :not() (e.g., span:not(:only-child): span elements that are not the sole child within their parent, potentially having neighboring span or i elements…)

Points to consider:

  • This workaround may not be applicable to all styles and scenarios :/
  • While adding a class to the parent element (as recommended by Amit) might be easier, there are instances where modifying the markup isn't feasible or where a CSS approach is more straightforward than adjusting the backend/frontend functions responsible for generating the markup (even though maintaining code could become more challenging in such cases).

Codepen

/* CSS from question (example #1) */
.on-link > li > a {
  display: inline-block;
  padding: 3px 5px;
  background-color: lightgreen;
}

/* Example #2 */

/* Targets i+span */
.on-children i {
  /*padding: 3px 0 3px 5px;*/
  background-color: lightblue;
}

.on-children i + span {
  /*padding: 3px 5px 3px 0;*/
  background-color: pink;
}

/* Selects any span without an icon (neither before nor after)
Note: :first-child would accommodate an icon placed at the end of the link */
.on-children span:only-child {
  padding: 3px 5px;
  background-color: tomato;
}

/* Demonstration */
.on-children i:before {
  content: 'i ';
}
<h1>Styles link (original styles from OP)</h1> 
<ul class="on-link">
  <li>
      <a id="btn-other-1" href="#">            <!–- I do not want apply css for this anchor tag because it has i inside –->
          <i class="fa fa-check" aria-hidden="true">
          </i><span>Other stuff-1? </span>
      </a>
  </li>
  <li>
      <a id="btn-other-2" href="#">
          <span>Other stuff-2</span>
      </a>
  </li>
</ul>

<hr>

<h1>Styles children of link (my answer)</h1>
<ul class="on-children">
  <li>
      <a id="btn-other-1" href="#">            <!–- I do not want apply css for this anchor tag because it has i inside –->
          <i class="fa fa-check" aria-hidden="true"></i><span>Other stuff-1?</span>
      </a>
  </li>
  <li>
      <a id="btn-other-2" href="#">
          <span>Other stuff-2</span>
      </a>
  </li>
</ul>

Answer №3

Make sure to look for combinators in this link: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors, although there may not be a direct combinator available.

An easy solution would be to assign a dummy classname to anchors with the i tag and a different one to anchors without the i tag.

<li>
    <a id="btn-other-1" href="#" class="itag">            <!–- I do not want apply css for this anchor tag because it has i inside –->
        <i class="fa fa-check" aria-hidden="true"></i>   
        <span> Other stuff-1? </span>
    </a>
</li>
<li>
    <a id="btn-other-2" href="#" class="noitag">
        <span> Other stuff-2 </span>
    </a>
</li>

Then you can use it like this.

.dropdown-menu > li > a.noitag {
  padding: 3px 5px;
}

Answer №4

If the first element is a li, you can target it using the :first-child selector

.dropdown-menu > li:first-child > a {
  padding: 0;
}

Alternatively, you can differentiate by using the id or class name of the a tag

<li>
    <a id="btn-other-1" href="#" class="icon">            <!–- I do not want apply css for this anchor tag because it has i inside –->
        <i class="fa fa-check" aria-hidden="true"></i>   
        <span> Other stuff-1? </span>
    </a>
</li>
<li>
    <a id="btn-other-2" href="#">
        <span> Other stuff-2 </span>
    </a>
</li>

.dropdown-menu > li > a:not(.icon) {
      padding: 3px 5px;
}

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

hiding form fields using javascript

As a beginner in javascript, I am facing a challenge with a set of checkboxes in an HTML form. These checkboxes are generated dynamically from a python script. Among them, there is a checkbox labeled "N/A" that I want to hide automatically when any other c ...

A guide to efficiently filling multiple rows of images with different heights while preserving their aspect ratio

I am facing a design challenge that I believe can be solved using CSS, although it might require some Javascript. My issue involves a gallery of images with varying sizes and proportions. I would like to achieve the following: Distribute the images in m ...

What is causing the QJsonValue(undefined) to be returned?

After sending a request to the API for bid price, I am receiving an undefined QJsonValue and unable to display it later. Can anyone help me pinpoint where I might be going wrong? { QApplication a(argc, argv); MainWindow w; w.show(); QNetwor ...

React - Obtain User Login Details and Verify

I am working on a React project that includes a Login Form. The code has been organized into small components for reusability, but I am unsure of how to retrieve and validate user credentials (username and password). Is there a method available to validate ...

Modify the indentation format in CSS/JS

When the Tab key is pressed in an HTML page and the tabbed link gets highlighted, is it feasible to customize the style of that highlight? ...

Avoid HTML code injection in an ExtJS4 grid by properly escaping the href attribute

I am facing an issue with escaping HTML in my Extjs grid. I have used the following configuration : return Ext.String.htmlEncode(value); In the renderer of my column, this method works perfectly for simple HTML tags like h1, b, i, etc. However, if I in ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

Is misbehavior expected at approximately 600 pixels in width?

What is happening with my website when the width is minimized, and how can I resolve it? Issue The website appears fine on mobile devices and full screens, but at reduced sizes, the background image disappears and the top bar behaves strangely (with the l ...

What are the steps for implementing the Ionic 2 Pulling Refresher feature in my application?

Hey everyone, I'm currently working on developing a mobile app using AngularJS 2/Ionic2. I am facing an issue with implementing a pull-to-refresh feature in my app. We followed the steps outlined in this link, and while we were able to get the page to ...

What could be causing my handle button to slide off the timeline towards the right?

I'm facing an issue with my volume bar component where the slider button is rendering outside of the timeline instead of on top of the progress bar. I need assistance in adjusting its position. // Here is the code for my volume bar component: import ...

Allow only specified tags in the react-html-parser white list

Recently, I've been working on adding a comments feature to my projects and have come across an interesting challenge with mentioning users. When creating a link to the user's profile and parsing it using React HTML parser, I realized that there ...

Making an entire webpage background clickable using just HTML and CSS

Is there a way to make the entire background of the page clickable using just HTML and CSS? <div style="position: fixed; top:0px; left:0px; z-index: -1; background: url() center center no-repeat; width: 100%; height:100%;"> <a href='http ...

Integrating Labels on External Websites with ASP.NET

I have been developing a website that needs to display a counter on the home page. To accomplish this, I used an asp label that counts and displays the database records (e.g. 180000) with no issues at all. However, now I am facing a new challenge. I want ...

Tips for customizing css for image tags

Here is the CSS code I used for images: img { border: none; max-width: 100%; height: auto !important } To override specific image styles, I added this at the bottom: .locals-list>img { height: 35px; } Below is the HTML code I am work ...

What is the process for altering the active status in pagination?

How can I make the active class in my pagination appear in red? Here's the code snippet I have: In my script.js file: $(".pagination").append("<li class='page-item' id='previous-page'><a class='page-li ...

I'm having trouble getting this text to align properly next to the image. Plus, I can't seem to achieve a horizontal screen alignment either

There seems to be an answer available, but I'm clearly not understanding it, so I've come here seeking further explanation and assistance. CSS can be quite complex, right? Here's a screenshot of my current project: https://i.stack.imgur.com/ ...

What is the expected output format for htmlspecialchars?

When I try the following: echo (htmlspecialchars("andreá")); I expect to see So, assuming that if I do echo (htmlspecialchars_decode("andreá")); I would get andreá. However, instead of the expected result, I see Additionally, when I run echo ...

Update content and image when clicking or hovering using Javascript

I have successfully implemented an image change on mouseover using javascript. However, I am facing a challenge in adding a description below the image upon mouseover or click. I do not have much experience with jQuery and would appreciate any help in so ...

What is the best way to click on a specific webElement in a group of webElements using Python Selenium?

After discovering how to locate a subelement of an element using Selenium in python through this informative Stack Overflow post, I am now eager to take my skills to the next level. Selenium Get WebElement inside a WebElement My goal is to be able to exe ...

Establishing a unique title and favicon for non-HTML files on a website

Is there a way to specify a title and favicon for non-HTML files on a website? For instance, what if I have a link like https://example.com/files/image-or-something.png. In Chrome, the default behavior is to display the URL of the file as the title, with ...