• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

How to Overwrite CSS Grid Properties with JavaScript?

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
When working with CSS and JavaScript, it can sometimes be tricky to modify CSS properties directly. In this blog, we'll address a common issue where you might be trying to change a CSS property like 'grid-template-columns' but are stuck due to unexpected behavior.

Understanding CSS Grid Properties


CSS Grid Layout is a powerful layout system that allows for complex designs. The property grid-template-columns is used to define the number and size of the columns in a grid layout. The unusual behavior you're encountering with grid-template-column stems from its singular and plural forms. The correct property to define column structure in grid layout is grid-template-columns, not grid-template-column. Understanding this distinction is crucial for successfully applying styles.

Why Your Changes Aren't Taking Effect


In your CSS stylesheet, you initially defined the grid with more columns than you want:

.grid-container {
display: grid;
grid-template-columns: auto auto auto auto auto auto;
}


When you attempt to modify this in your JavaScript code, you are using grid-template-column, which doesn’t correspond to the actual property you defined. This is likely why your changes are not being applied as expected. JavaScript is not able to find and overwrite the correct property, resulting in the grid still displaying as originally styled.

Step-by-Step Solution to Fix the Issue


To successfully modify the grid-template-columns property, ensure you reference it correctly in your JavaScript code. Here’s how to do it step by step:

1. Create a Reference to the Stylesheet


You've already started correctly with this code snippet:

// create a reference to linked stylesheet
const stylesheet = document.styleSheets[0];
const rules = stylesheet.cssRules || stylesheet.rules;

2. Loop Through Style Sheet Rules


You will loop through the rules to find the correct class and modify its properties:

for (let i = 0; i < rules.length; i++) {
if (rules.selectorText === '.grid-container') {
// Changing background color to yellow
rules.style['background-color'] = 'yellow';
// Correctly changing grid-template-columns to update layout
rules.style['grid-template-columns'] = 'auto auto auto';
break;
}
}

3. Complete Code Example


Here’s the complete code for clarity:

// create a reference to linked stylesheet
const stylesheet = document.styleSheets[0];
const rules = stylesheet.cssRules || stylesheet.rules;

// loop through the style sheet reference to find the classes to be modified and modify them
for (let i = 0; i < rules.length; i++) {
if (rules.selectorText === '.grid-container') {
rules.style['background-color'] = 'yellow';
// Correctly overwrite the grid-template-columns value
rules.style['grid-template-columns'] = 'auto auto auto';
break;
}
}

Frequently Asked Questions (FAQ)

Can I modify other CSS properties using JavaScript?


Yes, you can modify most CSS properties using JavaScript by referencing the stylesheet and accessing the style object, just ensure you use the correct property names.

What’s the difference between grid-template-columns and grid-template-column?


grid-template-columns defines the size of the columns in a CSS grid layout, while grid-template-column is not a valid CSS property and should not be used.

How do I check if my changes applied correctly?


You can inspect the page using browser developer tools (F12) to check the computed CSS styles on your grid container. If the styles appear as modified, your code is working as intended.

This approach allows you to effectively manage your styles dynamically using JavaScript, ensuring a seamless user experience while interacting with your grid layouts.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу