5

Is there a way to export CSS and HTML code from a single page ?

2
  • 1
    depends on what you mean by 'export'. you can save the HTML via the browser's file menu Commented Aug 28, 2019 at 22:08
  • I mean extract an html and css code from page and apply this design to my page Commented Aug 29, 2019 at 7:26

3 Answers 3

3

I think you meant "extract" splitted css/js resources from html (instead of "export"). It's strange that nobody answers for such important for web industry question.

Usually, many teachers told you that you must construct html+js+css by hands with yourself in ideal code-style by eslint, or jscs, or sonarqube, or markup validator w3, or with some vacuum-ideal popular framework. But in real life you often start project from draft (MVP), and optimize it lately, so you need tools similar to reverse engineering for your own web project...

Such tools allow you to avoid big technical explanation to other programmers, refactor your web project (front-end part) to readable clean format, e.g. extract css/js from html/php.

  1. SnipCSS extension extracts all CSS styles associated with any portion of your HTML webpage (with help of Chrome DevTools protocol).

  2. Extract critical css extracts the CSS for above-the-fold content in order to render content to the user as fast as possible (with goal of speed up).

  3. Webpack js mini css extract plugin extracts into JS+CSS pairs (for webpack world).

  4. TexAu can Extract CSS and JavaScript from you website (from HTML on your hosting).

    • Create a free TexAu account.
    • List the profile URLs to auto-like.
    • Run the automation right away (and schedule it).
  5. Save your rendered HTML page in Chrome Ctrl + S. It usually allows to split some resources separately (CSS, JS, FONT, IMG).

  6. Use Chrome standard browser Console and Elements inspector. On Console you can see document.styleSheets object value to know external CSS file names.

  7. Figma export to html plugin helps you if you are from Figma world instead of Web world.

  8. Export wp page to static html helps you if you are from Wordpress world instead of Web real world.

  9. Extract inline and external styles with help of PHP (CSS, from source HTML): Extract css from html

  10. Extract styles with help of Perl (CSS, from source HTML): Extract style tag data using Perl

  11. Extract CSS styles with help of Java JSoup HTML parser (from source HTML): Extract CSS Styles from HTML using JSOUP in JAVA

  12. Extract CSS styles form HTML with Softdrink Lisp. Extreme way.

  13. HTTrack Website Copier is helpful to prepare a mirror of your website that already contains some CSS styles separated from HTML. However, if it does not, you can use other methods later after uploading to other host/localhost. It is useful if your MVP (draft) was with unpopular CMS.

Usually there are three types of CSS-like styles within HTML page: inline element styles, internal html styles and external html link css styles. Good way is to extract them all as external CSS files.

Update 3. I have created own simplified example of such extractor:

<?php
// HTML code containing inline, internal and external CSS styles
$html = "<HTML>
<head>

</head>
<body>

<style type=\"text/css\">
    h1 {
         color: red;
    }
</style>

<h1 class=\"hh html-regular-header h-1\" id=\"main-header\" style=\"font-size: 24px;\">Hello World!</h1>
<h2 class=\" hh html-regular-header  h-2\" style=\"color: skyblue; background-color: grey\">Hello, Underworld.</h2>
<p class=\"some simple\" style=\"color: blue;\">This is a paragraph.</p>
<div style=\"text-align: center;\">It is sample</div>
<style>
    p {
         font-size: 16px;
    }
</style>
<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">
</body>
</HTML>";

// Parse HTML code using DOMDocument
$dom = new DOMDocument();
$dom->loadHTML($html);

function getSimplePath ($tag, $deepMax = 3) {
    $nodeKey = '';
    if (!isset($tag) || empty($tag) || $deepMax <= 0) {
        return $nodeKey;
    }
    if (!empty($tag->nodeName) && $tag->nodeName[0] !== '#') {
        $nodeKey = strtolower($tag->nodeName);
        if ($nodeKey === 'body' || $nodeKey === 'head' || $nodeKey === 'html') {
            $deepMax = 0;
        }
    } else {
        $nodeKey = '*';
        $deepMax = -1;
    }
    $parentKey = '';
    $was = false;

    if ($tag->hasAttribute('id')) {
        $nodeKey .= '#' . $tag->getAttribute('id');
        $was = true;
    }

    if (!$was && $tag->hasAttribute('class')) {
        $nodeKey .= '.' . implode('.', explode(' ', preg_replace('/\s+/', ' ', trim($tag->getAttribute('class')))));
        $was = true;
    } else if ($tag->hasAttribute('class') && !empty(trim($tag->getAttribute('class')))) {
        $nodeKey .= '.' . (explode(' ', trim($tag->getAttribute('class')))[0]);
    }

    if (!$was || !$tag->hasAttribute('id')) {
        $parentKey = getSimplePath($tag->parentNode, $deepMax - 1);
        if (!empty($parentKey)) {
            $nodeKey = $parentKey . ' > ' . $nodeKey;
        }
    }

    return $nodeKey;
}

function fixInlineStyleContent ($styleStr) {
    $styleStr = trim($styleStr);
    while ($styleStr[strlen($styleStr) - 1] === ';') {
        $styleStr = trim(substr($styleStr, 0, strlen($styleStr) - 1));
    }
    
    $styleArr = explode(';', $styleStr);
    foreach ($styleArr as $key => $value) {
        $value = trim($value);
        if (strpos($value, '!important') !== false || strpos($value, ' important') !== false || strpos($value, '"') !== false || strpos($value, "'") !== false) {
            $styleArr[$key] = $value;
            continue;
        }
        $styleArr[$key] = $value . ' !important';
    }
    
    $styleStr = implode('; ', $styleArr) . ';';
    return $styleStr;
}

function printAndApplyCSS ($styles, $isExternal = false) {
    if (!isset($styles)) {
        return;
    }
    if (!empty($styles) && !is_array($styles)) {
        $styles = array($styles);
    }
    if (count($styles) == 0) {
        return;
    }
    if (count($styles) == 1 && strlen(trim($styles[0])) == 0) {
        return;
    }
    
    foreach ($styles as $cssPart) {
        if (!$isExternal) {
            echo htmlspecialchars($cssPart); // print css (for user 1)
            echo('<style type="text/css">' . $cssPart . '</style>'); // apply css
        } else { // TODO
            $cssPart = trim($cssPart);
            if ($cssPart[0] === '/' && $cssPart[1] === '*' && $cssPart[strlen($cssPart) - 2] === '*' && $cssPart[strlen($cssPart) - 1] === '/') {
                $cssPart = trim(substr($cssPart, 2, strlen($cssPart) - 4));
                echo htmlspecialchars('href=' . $cssPart);  // print css (for user 2)
                echo('<link rel="stylesheet" type="text/css" href="' . $cssPart . '">'); // apply external css
            } else {
                echo htmlspecialchars($cssPart);  // print css (for user 3)
            }
        }
    }
}


// Retrieve External styles:
$external_styles = [];
foreach ($dom->getElementsByTagName('link') as $link_tag) {
     if ($link_tag->hasAttribute('rel') && strtolower($link_tag->getAttribute('rel')) == 'stylesheet' && $link_tag->hasAttribute('href')) {
         $external_styles[] = '/*' . $link_tag->getAttribute('href') . '*/';
     }
}
    
// Retrieve Internal styles:
$internal_styles = [];
$internalStyleTags = [];
foreach ($dom->getElementsByTagName('style') as $style_tag) {
     $internal_styles[] = $style_tag->nodeValue;
     $internalStyleTags[] = $style_tag;
}
foreach ($internalStyleTags as $style_tag) {
     $style_tag->parentNode->removeChild($style_tag); // do this only on simple array
}

// Retrieve Inline styles:
$inline_styles = [];
foreach ($dom->getElementsByTagName('*') as $tag) {
     if ($tag->hasAttribute('style')) {
         $nodeKey = getSimplePath($tag);         
         $inline_styles[] = '' . $nodeKey . '{' . fixInlineStyleContent($tag->getAttribute('style')) . '}';
         $tag->removeAttribute('style');
     }
}


// Print results:
echo "<b>External styles: </b>";  printAndApplyCSS($external_styles, true);  echo "<br/>";

echo "<b>Internal styles: </b>";  printAndApplyCSS($internal_styles);  echo "<br/>";

echo "<b>Inline styles: </b>";  printAndApplyCSS($inline_styles);  echo "<br/>";

echo "<hr/>";
$body = $dom->documentElement->lastChild;
echo($dom->saveHTML($body));
?>
Sign up to request clarification or add additional context in comments.

Comments

1

In Chrome, Click File --> Save Page AS (command + s on mac or control + s on pc).

Comments

0

You can see the html code in the Page source. To export them just simple copy and paste.

CSS can be viewed by clicks on the link in element, as well as js:

<link rel="stylesheet" href="link_to_css">

You can click also right mouse button and then save as.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.