Home  >  Article  >  Web Front-end  >  How to Dynamically Adjust the Width of a CSS `:before` Selector with jQuery?

How to Dynamically Adjust the Width of a CSS `:before` Selector with jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-11-08 11:01:01705browse

How to Dynamically Adjust the Width of a CSS `:before` Selector with jQuery?

Dynamic Width Adjustment of CSS :before Selectors Using jQuery

Objective: Modify the width property of elements adorned with the :before CSS selector, specifically when it follows a particular class name.

Scenario: Consider the following CSS:

.column:before {
    width: 300px;
    float: left;
    content: "";
    height: 430px;
}

.column {
    width: 500px;
    float: right;
    padding: 5px;
    overflow: hidden;
    text-align: justify;
}

Task: Alter the width property of the :before selector associated with the .column class using jQuery, without impacting elements without the :before rule.

Solution:

As mentioned in the given answer, jQuery does not natively support direct modification of pseudo-class rules. However, you can circumvent this limitation by dynamically appending a new style element to the document's head:

$('head').append('<style>.column:before {width: 800px !important;}</style>');

This assigns a fixed width of 800px to the :before selector within the .column class. Note that the !important declaration overrides any existing styles.

Alternatively, you could use a plugin specifically designed for modifying CSS pseudo-class rules. While a specific plugin recommendation is unavailable, a web search for "jQuery pseudo-class manipulation" should yield suitable results.

The above is the detailed content of How to Dynamically Adjust the Width of a CSS `:before` Selector with jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn