Replace all existing CSS styling with my designated CSS selector

I am developing an application for various content management systems where I am unaware of the surrounding CSS and its selectors, yet I want my app to maintain a consistent appearance.

An issue I am facing is when an external selector targets one of my elements, such as button{height: 100px;}, and my selector button .class{width:100px;} does not specify the height attribute. In this case, the external selector adds this attribute to my buttons, altering their style.

This is just a basic example. You may suggest specifying the height in my selector as well, but I cannot include every possible attribute in my selectors to override any existing styles that may have been applied elsewhere.

You can view an example in this fiddle: https://jsfiddle.net/u4rvx6Lk/. Here, I do not want the first selector to apply border styling to my blue element, but it does so anyway.

I have attempted using all: unset; and all: initial;, but these solutions do not work reliably across all browsers, especially Internet Explorer.

I am also aware of scoped CSS, but I have found it to be inconsistent in resolving this issue.

(Additional Information: This is an Angular 1.x application that will primarily be integrated into WordPress CMS pages, and I compile my CSS using Sass.)

Answer №1

To solve my issue, I utilized the CSS property all with a value of revert.

.css-class {
    all: revert;
}

The explanation provided in the mozilla docs for revert was quite helpful:

The revert CSS keyword helps reset the cascade to mimic what would happen if there were no existing styles from the current style origin.

If you're using Firefox or Chrome, opting for unset is recommended:

.css-class {
    all: unset;
}

Check out browser hacks for information on "media query hacks" that can help determine the browser when seeking a cross-browser solution. Additionally, refer to this fiddle where the height property isn't inherited by the blue box:

This approach may prove beneficial for your project too.

Answer №2

Preventing CSS code from modifying your elements is a challenging task in the current state of the web. What you are really looking for is to sandbox your elements, ensuring they remain unaffected by external code.

One option to achieve this is by using an iframe, but this method can be cumbersome and not practical.

However, there is light at the end of the tunnel! The upcoming feature known as Shadow DOM will allow you to create custom elements and isolate them from the rest of your code. This concept is already utilized by elements like input and video behind the scenes, and soon we will have the ability to do the same.

Let's say we want to create a new element called solid-button.

<solid-button></solid-button>

Next, we need to define the content that goes inside our element using a template:

<template id="solid-button-src">
  <style>
    button {
      width: 100px;
      height: 100px;
      background-color: green;
      border: solid 1px black;
    }

  </style>
  <button></button>
</template>

We then utilize JavaScript to create the Shadow DOM and insert the template content into it:

customElements.define('solid-button', class extends HTMLElement {
  constructor() {
    super();

    const shadowRoot = this.attachShadow({
      mode: 'open'
    });
    const template = document.querySelector('#solid-button-src');
    const clone = document.importNode(template.content, true);
    shadowRoot.appendChild(clone);
  }
});

While this technique works in some browsers currently, it's not yet widely supported for production use. Users can style the solid-button element without affecting its internal content. If you have an updated browser, you can see this functionality in action below.

Although this solution may not be viable for immediate use, it holds promise for the future.

customElements.define('solid-button', class extends HTMLElement {
  constructor() {
    super();

    const shadowRoot = this.attachShadow({
      mode: 'open'
    });
    const template = document.querySelector('template');
    const clone = document.importNode(template.content, true);
    shadowRoot.appendChild(clone);
  }
});
button {
  height: 100px;
  width: 100px;
  background-color: red;
  border: solid 1px black;
}

.class1 {
  height: 100px;
  width: 100px;
  background-color: blue;
}

my-button {
  background: red; /* does nothing visible */
}
<button></button>
<button id="id1" class="class1"></button>
<solid-button></solid-button>
<solid-button class="class1"></solid-button>

<template>
  <style>
    button {
      width: 100px;
      height: 100px;
      background-color: green;
      border: solid 1px black;
    }

  </style>
  <button>
    <slot name="content"></slot>
  </button>
</template>

Answer №3

I managed to find a solution that worked for me. Many thanks for the helpful responses.

After trying out various options, I discovered that using all: initial instead of all: unset and revert was effective in my case.

In addition, I have decided to assign very specific names to my internal classes, such as class=my-project-class, in order to avoid conflicts with external class-selectors adding their own styles.

It's worth noting that this approach is not compatible with Internet Explorer.

You can check out the demonstration on this Fiddle: https://jsfiddle.net/Lvxxnh8r/13/

Answer №4

Check out this demo for a simple illustration. Unfortunately, the border is appearing on my blue element instead.

The reason why the border is being applied to the second box is because it's a button, which is where you specified the border in your CSS. This is just how CSS works. If you don't want the border on the second element, you either need to set border: 0; specifically on that element, or modify the original selector that sets the border on button to exclude the second box by using something like button:not(#id1).

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

Utilizing the float: left property for creating additional spacing in a responsive CSS layout

My frustration levels are off the charts as I struggle to understand why this code refuses to cooperate. As I work on setting up my personal website, I want everything to be perfectly responsive before I even think about adding my content. One major headac ...

Troubleshooting CSS navigation bar hamburger dilemma

Currently, I am facing an issue with a toggle button on my website. When I click on the hamburger menu, the navigation bar does not show up even though the toggle feature is working perfectly fine. I have tried combining different sources to solve this pro ...

Tips for positioning a Navbar in the middle of the screen at 90% width

I am struggling to center the navbar as a whole, rather than just the contents within it. Below is the CSS and HTML for my navbar. .navbar { border-radius: 10px 10px 30px 30px; background: #3CE18F; overflow: visible; position: fixed; bottom: ...

Unseen columns within an HTML table are also being included in the export

In my HTML table, I have included a drop-down feature for users to select the row they want to view, along with an export button that allows them to save the data in Excel format. During the exporting process, I encountered an issue where hidden rows were ...

Add a variety of icons to every item in a list using HTML

Is there a way to display multiple icons on the left side of each element, with the option to have none or many? If so, could you please guide me in the right direction. <header> <nav> <ul> <a href="http://localhost:4000 ...

Develop your website layout with Flexbox (Bootstrap 4.2), using stacked grid designs similar to the float: left method

For my Wordpress theme, I am utilizing Bootstrap 4.2 to design a basic grid layout for a list of blog posts. In my design, I have a Card that is double the height of others and I am attempting to 'float' two single-height cards beside it. Previ ...

I prefer to not have the box-shadow showing up on top of the navigation bar

Check out this cool demo: View Demo I am looking to add a shadow effect above the footer section, but not above the navigation bar. nav{ background-color: blue; height: 100px; } main{ box-shadow: 0px 0px 16px 2px rgba(0, 0, 0, 0.5); background- ...

Revisiting the display of input placeholders

Enabling the placeholder property on an input field allows the text to disappear when something is written and reappear when everything is deleted. Here's the question: Is it feasible to delay the reappearance of the placeholder text until after the t ...

Deleting a row from a table using TypeScript in Angular

I am currently working on a task management application and I am facing an issue with deleting a row when clicking the delete button. Below is the table structure in my HTML: <table *ngFor="let todo of todos; let i = index;" class="todo ...

Ways to troubleshoot the logic issue in the loop for my simple login interface

I have been able to successfully implement code that detects when a user enters an incorrect username or password, as well as granting access when the correct credentials are provided initially. However, there seems to be a logic error in my loop that prev ...

Tips for showcasing beautifully formatted XML content on a webpage

I have some XML data that I want to display on my website, but I'd prefer to show it in a styled format like a bootstrap table. However, I'm not sure how to go about doing this. Here's an example of the XML: <?xml version="1.0" encoding ...

What is the best way to choose the next adjacent element using a CSS selector with Python Selenium?

The structure of the DOM is as shown below: <ul> <li> <a href="#" role="button" class="js-pagination link" data-page="1">1</a> </li> <li> <a href="#" role="button" class="js-pagination link active" data ...

What could be the reason for the absence of a second alert appearing?

I have a small application that validates email addresses for the correct elements, but it's not displaying the confirmation message. $(document).ready(function(){ $("#sendButton").click(function(){ var name = $("#name").val(); ...

How should we arrange these components to optimize the overall aesthetic of this particular design?

My current progress on the code: Visit this link Desired design for reference: View design picture here I've experimented with position relative and margins, but these techniques have impacted the responsiveness of my webpage. What is the most eff ...

Is there a way to stop my <pre> code from being displayed on the page?

Currently, I am utilizing the google code prettifier found at http://code.google.com/p/google-code-prettify/ This tool functions similarly to stack overflow by enhancing and highlighting syntax when a block of code is input. However, I have encountered a ...

What is the process for obtaining the Rails response object within your code?

Is there a way to manipulate the response object from a controller in Rails? I have an example of how to access the response: class HomeController < ApplicationController after_filter :generate_html def index end def generate_html raise ...

Acquiring administrative authorization upon user login with PHP

I have developed a registration form and a login form using PHP. However, whenever I run this code, it displays the message "invalid username" when the username is invalid, or it says "your account isn't approved by admin yet." Can anyone please guide ...

Transferring information from user input to a table using AngularJS

I need assistance with AngularJS to transfer data from 2 input fields (name and last name) into a table row. <input type="text" ng-model="name"> <input type="text" ng-model="lastname"> Here is the structure of my table: <tabl ...

Creating a half drop and half brick pattern on canvas is a fun and easy way to add

I have successfully created an image using canvas https://i.sstatic.net/AIvSH.png Now I am looking to create a similar image using canvas https://i.sstatic.net/y8kGt.png I have included the code I have worked on so far. <div id="canvas_div" style=" ...

Display a specific message in a div when the input field is left empty

My goal is to create a div that mirrors the content of an input field. When I type "lalala" in the input, it should show up in the div, and this part is working fine. However, I also want the div to display "The input is empty" when the input itself is emp ...