База знанияИзпитен център
BGБългарски
Избери език13

CKTIS / CSS

DevTools: CSS инспектор, изчислени стилове и модел на кутията

Виж кои CSS декларации влияят на елемента, провери стойностите и размерите му и изпробвай принудително състояние и временни промени на стиловете.

Версия: Browser DevTools workflow; UI and feature availability vary by browser and version

Синтаксис

DevTools is a browser interface, not CSS syntax. The available controls and the names and locations of panels depend on the browser and its DevTools version, not on the CSS specification version. Typical workflow: Inspect an element → Rules or Styles → Computed → box model. To test a state rule such as `.demo:hover { background-color: #ffe8a3; }`, force `:hover` in the inspector.

DevTools са инструментите за разработчици в браузъра, а не синтаксис на CSS. Щракни с десния бутон върху елемент и избери командата за проверка или го избери в DOM дървото. В Rules или Styles ще видиш правилата, чиито селектори съвпадат с елемента, и съответните наследени стилове. Зачеркната декларация може да е отстъпила пред друга в каскадата; провери и дали инструментът не отбелязва грешка.

В Computed виждаш стойностите на свойствата за избрания елемент, а не само текста в стиловия файл. Не отъждествявай панела с формалния етап на изчислената стойност в CSS: някои показани стойности вече може да отчитат оформлението на страницата. Имената и местоположението на панелите зависят от браузъра.

Диаграмата на модела на кутията показва съдържанието, вътрешния отстъп (padding), рамката (border) и външния отстъп (margin). При box-sizing: content-box свойството width задава ширината на съдържанието. За ширината между външните ръбове на рамката прибави вътрешните отстъпи и дебелината на рамката отляво и отдясно, но не и външните отстъпи.

Активирай принудително :hover в инспектора, за да изпробваш съответните стилове, без да държиш показалеца над елемента. Промени или изключи декларация в Rules или Styles, за да видиш ефекта веднага. Обикновената редакция на живо не променя изходния файл и изчезва при презареждане. За да запазиш промяната, нанеси я в изходния файл или използвай изрично функция за запис, ако инструментът предлага такава.

Примери

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Inspect the CSS box model</title>
  <style id="demo-styles">
    .demo {
      display: block;
      box-sizing: content-box;
      width: 160px;
      padding: 12px;
      border: 2px solid #333;
      margin: 16px;
      background-color: #e7f0ff;
    }

    .demo:hover {
      background-color: #ffe8a3;
    }
  </style>
</head>
<body>
  <div class="demo" role="img" aria-label="Demo box"></div>
  <p id="measurements"></p>
  <script>
    // Measure isolated copies so the visible box stays available for inspection.
    const css = document.getElementById('demo-styles').textContent;
    const source = `<!doctype html><style>${css}</style><div class="demo"></div>`;
    const report = document.getElementById('measurements');

    function loadCopy() {
      return new Promise(resolve => {
        const frame = document.createElement('iframe');
        frame.setAttribute('aria-hidden', 'true');
        frame.style.cssText = 'position:fixed;left:-1000px;top:0;width:400px;height:160px;visibility:hidden;pointer-events:none';
        frame.addEventListener('load', () => resolve(frame), { once: true });
        frame.srcdoc = source;
        document.body.append(frame);
      });
    }

    function measure(frame) {
      const box = frame.contentDocument.querySelector('.demo');
      const style = frame.contentWindow.getComputedStyle(box);
      const sides = ['Top', 'Right', 'Bottom', 'Left'];
      function uniform(property, suffix = '') {
        const values = sides.map(side => style[property + side + suffix]);
        if (!values.every(value => value === values[0])) {
          throw new Error(`${property} differs by side`);
        }
        return values[0];
      }
      return {
        background: '#' + style.backgroundColor.match(/\d+/g)
          .map(component => Number(component).toString(16).padStart(2, '0')).join(''),
        content: style.width,
        padding: uniform('padding'),
        border: uniform('border', 'Width'),
        margin: uniform('margin'),
        outer: `${box.getBoundingClientRect().width}px`
      };
    }

    async function showMeasurements() {
      const frame = await loadCopy();
      let initial, hover, edited;
      try {
        initial = measure(frame);
        const [boxRule, hoverRule] = frame.contentDocument.styleSheets[0].cssRules;
        const originalSelector = hoverRule.selectorText;
        // Page scripts cannot force a DevTools state. Match the same rule
        // at the same specificity in this copy to measure its effect.
        hoverRule.selectorText = '.demo.demo';
        hover = measure(frame);
        hoverRule.selectorText = originalSelector;
        if (hover.background === initial.background ||
            JSON.stringify({ ...hover, background: initial.background }) !== JSON.stringify(initial)) {
          throw new Error('The hover rule did not change only the background');
        }
        boxRule.style.padding = '20px';
        edited = measure(frame);
      } finally {
        frame.remove();
      }

      // A fresh document reads the original stylesheet, not the live edit.
      const fresh = await loadCopy();
      let restored;
      try {
        restored = measure(fresh);
      } finally {
        fresh.remove();
      }
      if (JSON.stringify(restored) !== JSON.stringify(initial)) {
        throw new Error('A fresh load did not restore the original measurements');
      }

      report.textContent = [
        `Expected in a blank page with no other author styles: with the pointer outside the box and no forced state, the background is ${initial.background}.`,
        `The content is ${initial.content} wide, with ${initial.padding} padding, a ${initial.border} border, and a ${initial.margin} margin on each side.`,
        `The border-to-border width is ${initial.outer}, excluding margin.`,
        `Forcing :hover changes the background to ${hover.background} without changing the width.`,
        `Editing padding to ${edited.padding} in Rules/Styles increases the border-to-border width to ${edited.outer}.`,
        `Reloading without saving or overrides restores ${restored.padding} padding and a ${restored.outer} border-to-border width.`
      ].join(' ');
    }

    showMeasurements().catch(error => {
      report.textContent = `Could not produce the box measurements: ${error.message}.`;
    });
  </script>
</body>
</html>

Резултат

Expected in a blank page with no other author styles: with the pointer outside the box and no forced state, the background is #e7f0ff. The content is 160px wide, with 12px padding, a 2px border, and a 16px margin on each side. The border-to-border width is 188px, excluding margin. Forcing :hover changes the background to #ffe8a3 without changing the width. Editing padding to 20px in Rules/Styles increases the border-to-border width to 204px. Reloading without saving or overrides restores 12px padding and a 188px border-to-border width.

Отвори HTML примера в браузър. Избери примерния елемент в инспектора, отмести показалеца и сравни Computed с диаграмата. Принудителното активиране на `:hover` променя само фона. Изключи принудителното състояние и промени `padding` от `12px` на `20px`: ширината с рамката, но без външните отстъпи, нараства от `188px` на `204px`. Презареди без запис или трайни замени: стойностите `12px` и `188px` се възстановяват.

Свързани уроци

  • CSS · Урок 8 · Начално · Версия: 3

Източници