Showing posts with label sass. Show all posts
Showing posts with label sass. Show all posts

Sunday, September 2, 2018

Can't page break to work without messing up the table formatting

Leave a Comment

I have been having issues with page breaks in tables. Thought I had a solution as it was working fine in this SO question:

Inserting a page break into of <table> in React app

This worked fine for a table with one column, but nowt that I am working with multiple columns, it is a mess.

Basically I have to include display: block to get the page break to work properly, but that makes it go from a well formatted table to this:

enter image description here

I have gone down the list in MDN just trying anything that might work.

https://developer.mozilla.org/en-US/docs/Web/CSS/display

Furthermore, page breaks are only working when on their own separate <tr> which is undesirable since it generates a blank page. Got this sorted out by moving the pagebreak to the <tr> instead of the <td>.

I haven't been able to resolve these issues; any suggestions on how to approach this problem?

Not sure how useful a JSFiddle will be given the printing issue, but here is the compiled HTML. I can never get JSFiddle working with React:

https://jsfiddle.net/5gz62d91/

Best would probably be the Github repo:

https://github.com/ishraqiyun77/page-breaks

Here is the code separately:

import React, { Component } from 'react'; import ReactDOM from 'react-dom';  import styles from '../assets/scss/app.scss';  class PageBreakIssues extends Component {      // Render the data points     renderDataPoint() {         let dataPoint = [];         for (let i = 1; i <= 3; i++) {             let num = (Math.random() * 100).toFixed(2);             dataPoint.push(                 <td className='data-point' key={ i }>                     { num < 25 ? null : num }                 </td>             )         }         return dataPoint;     }      // Start generating the row data     renderDataRow() {         let dataRow = [];         for (let i = 1; i <= 5; i++) {             dataRow.push(                 <tr key={ i }>                     <td className='data-name' colSpan='3' key={i}>Test - { i }</td>                     { this.renderDataPoint() }                 </tr>             )         }         return dataRow;     }      // Start generating table sections with the section name     // COMMENT THIS OUT TO TRY WITOUT ADDING A BLANK ROW     renderSections() {         let sections = [];         for (let i = 1; i <= 10; i++) {             sections.push(                 <tbody key={ i }>                      <tr key={ i }>                         <td colSpan='7' className='section-name' key={i} >                             Section - { i }                         </td>                     </tr>                     { this.renderDataRow() }                     {                         i % 2 === 0                             ?                             <tr className='pagebreak'>                                 <td colSpan='7'></td>                             </tr>                             :                             null                     }                 </tbody>             )         }            return sections;     }      // Start generating table sections with the section name     // UNCOMMENT THIS SECTION TO TRY WITHOUT INSERT BLANK TR     // renderSections() {     //     let sections = [];     //     for (let i = 1; i <= 10; i++) {     //         sections.push(     //             <tbody key={i}>     //                 <tr key={i}>     //                     <td colSpan='7' className={ i % 2 === 0? 'section-name pagebreak' : 'section-name'} key={i} >     //                         Section - {i}     //                     </td>     //                 </tr>     //                 {this.renderDataRow()}     //             </tbody>     //         )     //     }     //     return sections;     // }      // Render the table with <th>     render() {         return (             <table>                 <thead>                     <tr>                         <th colSpan='3'>Results</th>                         <th>1</th>                         <th>2</th>                         <th>3</th>                     </tr>                 </thead>                 { this.renderSections() }             </table>         )     } }  ReactDOM.render(<PageBreakIssues />, document.getElementById('app')); 

@mixin borders {     border: 1px solid black; }  %borders {     @include borders; }  table {     border-spacing: 0;      th {         text-align: center;     }      tr {         th{             @extend %borders;         }          td {             @extend %borders;             &.data-name {                 padding: 3px 100px 3px 3px;             }              &.data-point {                 text-align: center;                 padding: 3px 10px;             }              &.section-name {                 background-color: #999;             }         }     } }  @media print {     tr {         display: block;     }      .pagebreak {         break-before: always !important;         page-break-before: always !important;         page-break-inside: avoid !important;     } } 

1 Answers

Answers 1

I faced similar problem before, as can't find any solution from net, I come up with a somehow hard-coding method.

Please take this as fallback, if no other available solutions are posted before your deadline.

You need to put back the page-break to tbody and make it as following.

HTML:

... </tbody> <tbody class="pagebreak">     <tr>         <td colspan="7"></td>     </tr> </tbody> <tbody> ... 

SCSS

@media print {      thead {       display:table;       width: 100%;       th{         text-align: center;         padding: 3px 10px;       }     }      tbody {       display:block;     }     .pagebreak {         height:0px;         break-before: always !important;         page-break-before: always !important;         page-break-inside: avoid !important;     } } 

My method's main idea is changing tbody to display:block (as usual), but adding the .pagebreak to target tbody as well.

However, this method unattach tbody from the table and thus no longer align with thead. That's why I need to add back padding: 3px 10px; to thead so as to simulate the cell size of tbody

The whole working example based on your code is quite long, so I put in a JSfiddle.

Read More

Monday, October 16, 2017

Webpack source-map does not resolve sass imports

Leave a Comment

I have webpack configured to transpile scss -> css, but sourcemap generated by webpack does not resolve scss @imports.

webpack.config.js:

const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin');  const outputPath = path.join(__dirname, 'dist');  module.exports = {     devtool: 'source-map',     entry: ['./src/main.scss'],     target: 'web',     output: {         filename: 'js/[name].bundle.js',         path: outputPath     },     module: {         rules: [             { // sass / scss loader for webpack                 test: /\.(sass|scss)$/,                 loader: ExtractTextPlugin.extract([                     {                         loader: 'css-loader',                         options: {                             url: false,                             import: true,                             minimize: true,                             sourceMap: true,                         }                     },                     'sass-loader'                 ])             },         ]     },     plugins: [         new ExtractTextPlugin({ // define where to save the file             filename: 'css/[name].bundle.css',             allChunks: true,         })     ] }; 

main.scss:

@import 'foo'; 

_foo.scss:

h1 { color: red; } 

However, in Chrome dev tools, I see a reference to main.scss where I expect reference to _foo.scss - see the screenshot below:

_foo.scss not resolved

Compiled demo: http://store.amniverse.net/webpacktest/

2 Answers

Answers 1

You have sass-loader there, switch it with:

{    loader: 'sass-loader',    options: {      sourceMap: true    } } 

And I think that should work.

Answers 2

You should not use extractTextPlugin when you are in dev mode. Please make extra configs for dev and production mode. In production the use of extractTextPlugin is fine but in dev mode it is not necessary and can lead to other features not working. So instead use the style-loader.

Also - I am not shure if that fixes your problem - try to use importLoaders prop on the css loader. Look here for more info:

https://github.com/webpack-contrib/css-loader#importloaders

const path = require('path');  const outputPath = path.join(__dirname, 'dist');  module.exports = {     devtool: 'source-map',     entry: ['./src/main.scss'],     target: 'web',     output: {         filename: 'js/[name].bundle.js',         path: outputPath     },     module: {         rules: [             { // sass / scss loader for webpack                 test: /\.(sass|scss)$/,                 loader: [                     {                         loader: 'style-loader',                         options: {                           sourceMap: true                         }                     },                     {                         loader: 'css-loader',                         options: {                             url: false,                             import: true,                             minimize: true,                             sourceMap: true,                             importLoaders: 1,                         }                     },                     {                        loader: 'sass-loader',                        options: {                          sourceMap: true                        }                     }                 ]             },         ]     } }; 
Read More

Tuesday, August 22, 2017

formular to calculate width/height (relative to parent) of container with translateZ inside of parent container with perspective

Leave a Comment

What is the formular to calculate the widths/heights of child elements with translateZ inside of parent container with set perspective (keyword: "parallax") relative to its parents width/height?

I'd like to create a site with parallax effect on both axis. I was able to figure out everything i need for my mockup except one thing. How to calculate the childrens widths/heights when its above 100%. Because of parents perspective and childrens translateZ the childrens widths/heights visually don't align with parents width/height anymore.

The formular to scale the child elements is: 1 + (translateZ * -1) / perspective. But i was not able to find a formular for width/height. BTW: When childrens widths/heights <= 100% everything works fine.
But see the result on the image below when width >= 100% (containers have top offset to make things visible).

enter image description here

To be correct the approach in my particular case is to let all child elements have visually the same widths/heights.


in SASS (preferred): PEN or SassMeister
in CSS: PEN


links from the specs that could help:
https://www.w3.org/TR/css-transforms-1/#recomposing-to-a-3d-matrix
https://www.w3.org/TR/css-transforms-1/#mathematical-description


"Googled" a lot but didn't find anything pointing me to the right direction. Thanks in advance...

html, body {    height: 100%;    overflow: hidden;    width: 100%;  }    #projection {    perspective: 1px;    perspective-origin: 0 0;    height: 100%;    overflow: auto;    width: 100%;  }    .pro {    transform: scale(1) translate(0px, 0px) translateZ(0px);    height: 100%;    position: absolute;    transform-origin: 0 0;    transform-style: preserve-3d;    width: 100%;  }    .pro--1 {    transform: scale(4) translate(0px, 0px) translateZ(-3px);    width: 110%;  }    .pro--2 {    transform: scale(3) translate(0px, 50%) translateZ(-2px);    width: 110%;  }    .pro--3 {    transform: scale(2) translate(0px, 100%) translateZ(-1px);    width: 110%;  }    .pro {    background: #333;    box-shadow: inset 0 0 0 5px orange;    color: orange;    font-size: 4em;    line-height: 1em;    text-align: center;  }    .pro--2 {    background: rgba(75, 75, 75, 0.5);    box-shadow: inset 0 0 0 5px green;    color: green;    line-height: 4em;  }    .pro--3 {    background: rgba(75, 75, 75, 0.5);    box-shadow: inset 0 0 0 5px white;    color: white;    line-height: 7em;  }
<div id="projection">    <div class="pro pro--1">pro--1</div>    <div class="pro pro--2">pro--2</div>    <div class="pro pro--3">pro--3</div>  </div>

SASS

@mixin  projection($translateZ: 0, $translateX: 0, $translateY: 0, $width: 0, $height: 0, $perspective: $perspective)    // strip and sanitize units for further calculations   // units must be "px" for both $translateZ and $perspective   $unit: unit( $translateZ )   @if '' != $unit     $translateZ: $translateZ / ($translateZ * 0 + 1)     @if 'px' != $unit       @warn '$translateZ must have "px" as unit!'    $unit: unit( $perspective )   @if '' != $unit     $perspective: $perspective / ($perspective * 0 + 1)     @if 'px' != $unit       @warn '$perspective must have "px" as unit!'    $unit: 0px // yeah - technically this is no unit    // calculate scaling factor   $scale: 1 + ($translateZ * -1) / $perspective    // sanitize units for translateX, translateY, translateZ   $translateZ: $translateZ + $unit   @if unitless( $translateX )     $translateX: $translateX + $unit   @if unitless( $translateY )     $translateY: $translateY + $unit    // render css "transform: scale() translate(x, y) translateZ()"   transform: scale( $scale ) translate($translateX, $translateY) translateZ( $translateZ + $unit )  $width: 110% // 100% works like a charme $translateZ--1: -3 // "px" will be added in mixin $translateZ--2: -2 $translateZ--3: -1 $perspective: 1  html, body   height: 100%   overflow: hidden   width: 100%  #projection   perspective: $perspective + 0px   perspective-origin: 0 0   height: 100%   overflow: auto   width: 100%  .pro   @include projection()   height: 100%   position: absolute   transform-origin: 0 0   transform-style: preserve-3d   width: 100%  .pro--1   @include projection( $translateZ--1 )   width: $width  .pro--2   @include projection( $translateZ--2, 0, 50% )   width: $width  .pro--3   @include projection( $translateZ--3, 0, 100% )   width: $width 

2 Answers

Answers 1

You've already solved your problem. Your code does exactly what you need it to do, it's just a CSS layout issue now.

https://codepen.io/anon/pen/xLWGzp?editors=0100

Because of the perspective changes, if you hang everything off the x-axis center everything will begin to line up properly:

(I'm just adding in the code changes here, I've left everything else the same)

#projection     perspective-origin: center top  .pro     transform-origin: center top 

Now everything's lining up better, but it's still a bit off - you can change the $width variable to anything other than 100% to see the problem (60% is a good one)

So the problem now is just due to the positioning of the elements, when you set position: absolute they're default positioned to the left, change the width and add scale and transform and you get this equal-width/not-equal-position, so center them by adding:

#projection     position: relative  .pro     left: 50%     margin-left: $width * -.5 

(info here as to why that works to center: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/)

So now jiggle $width around to double-check, I tested it from 20% up to 150% and it works fine.

Answers 2

I have changed the style slightly, to make things more visible.

The result seems ok for me. May be I am misunderstanding something ?

html, body {    height: 100%;    overflow: hidden;    width: 100%;  }    #projection {    perspective: 1px;    perspective-origin: 0 0;    height: 50%;    overflow: visible;    width: 50%;    margin-left: 50px;    background-color: grey;  }    .pro {    transform: scale(1) translate(0px, 0px) translateZ(0px);    height: 50%;    position: absolute;    transform-origin: 0 0;    transform-style: preserve-3d;    width: 100%;  }    .pro--1 {    transform: scale(4) translate(0px, 0px) translateZ(-3px);    width: 110%;  }    .pro--2 {    transform: scale(3) translate(0px, 120%) translateZ(-2px);    width: 110%;  }    .pro--3 {    transform: scale(2) translate(0px, 240%) translateZ(-1px);    width: 110%;  }    .pro--1 {    background: rgba(0, 0, 75, 0.5);    color: blue;    line-height: 1em;    text-align: center;  }    .pro--2 {    background: rgba(0, 75, 0, 0.5);    color: green;    line-height: 4em;  }    .pro--3 {    background: rgba(75, 0, 0, 0.5);    color: red;    line-height: 7em;  }
<div id="projection">    <div class="pro pro--1">pro--1</div>    <div class="pro pro--2">pro--2</div>    <div class="pro pro--3">pro--3</div>  </div>

Read More

Monday, July 3, 2017

Sass: $color-darken with HSL color codes

Leave a Comment

I know how to use built-in functions for determining a darker color from a hex code. But how to do this with hsl? I have three colors, one primary, one darker and a lighter one. I need to write a function to calculate the difference between them and get a lighter and darker shade for them. So when I add another color code, it'll give me same percentage for lighter and darker shade.

As I understand from Sass documentation, I first need a function to get hue, saturation, and lightness of my base color, right? But what then?

These are my colors in hex:

$base: #7760BF; $base-darker: #483584; $base-lighter: #b5a9dc; 

And here they are in hsl, just in case:

$base: hsl(255, 43%, 56%); $base-darker: hsl(254, 43%, 36%); $base-lighter: hsl(254, 42%, 76%); 

Can someone help me out?

1 Answers

Answers 1

In Sass, types are converted automatically. Color functions from the Sass standard library will accept any color, rgb or hsl.

At first to generate darker and lighter colors, you can use darken and lighten. I made an example here.

enter image description here

Then to know the lightness difference between colors to generate new colors with the same difference, you can use lightness.

@function get-lightness-diff($base, $color) {     @return lightness($base) - lightness($color); }  @function get-variant($color, $diff) {     @if ($diff < 0) {         @return darken($color, -$diff);     } @else {         @return lighten($color, $diff);     } }  @function get-variants($color, $diff) {     $ret: ();     $ret: map-merge($ret, ( darker: get-variant($color, -$diff) ));     $ret: map-merge($ret, ( lighter: get-variant($color, $diff) ));     @return $ret; }  @function get-variants-from-set($color, $darker, $base, $lighter) {     $darker-diff: get-lightness-diff($base, $darker);     $lighter-diff: get-lightness-diff($base, $lighter);      $ret: ();     $ret: map-merge($ret, ( darker: get-variant($color, $darker-diff) ));     $ret: map-merge($ret, ( lighter: get-variant($color, $lighter-diff) ));     @return $ret; }  $base: hsl(255, 43%, 56%); $base-lighter: hsl(255, 43%, 66%); $base-darker: hsl(255, 43%, 46%);  // Get a lightness diff, from the light color for example $diff: get-lightness-diff($base, $base-lighter);  // Variants: contains a map with 'darker' and 'lighter' colors. $variants: get-variants($base, $diff); // Or create your lighter/darker variants manually: $darker: get-variant($base, -10%); $lighter: get-variant($base, 10%);  // Or all-in-one: create your variants from an other set of colors: $other-base: hsl(255, 33%, 33%); $other-variants: get-variants-from-set($other-base, $base-darker, $base, $base-lighter); 

I made an other example here, but you may have to adapt it to make it fit your needs.

Variants

Read More

Thursday, April 6, 2017

(S)CSS architecture: alternative backgrounds styling

Leave a Comment

I'm using 'component' approach to CSS as in SMACSS / ITCSS, I'm still scratching my head about styling sections with alternative (dark) background.

e.g. Stripe has regular (dark text on white) and alternative (white text on dark) sections.

enter image description here

As I understand there are options assuming HTML:

<section class="dark">     <h2>Title</h2>     <p>Text</p>     <a href="#" class="btn">Action</a> </section> 

Style in context of section, e.g.:

.dark h2, .dark p, .dark btn {   color: white; } 

But a) context styling is not recommended; b) where does one put the styles? (Harry Roberts argues that in component's file)

Create alternative-colored components with modifiers

And change the HTML, e.g.:

.title--alt-color {color: white;} .text--alt-color {color: white; } ...  

But a) it doesn't work when you don't know which components will go in there; b) more work of managing HTML.

Maybe there is a better way to handle this?

3 Answers

Answers 1

What you're asking for is essentially to style a component within a section based on the section itself. Unfortunately this is impossible with CSS, as there is no parent selector in CSS. However, there is the inherit value, which allows you to style a component based on the rules defined by its parent - perfect for component-driven CSS.

In my opinion, the best way you can go about alternating background styling is to make use of the :nth-of-type pseudo-class on <section>:

section:nth-of-type(2n) {    background: #464646;    color: #fff;  }  
<section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>

Considering :nth-of-type makes use of math to target elements, you can access literally any combination of elements you would like:

// Style every second element, starting with the first element section:nth-of-type(2n - 1)  // Style every third element, starting with the second element (2, 5, 8, etc.) section:nth-of-type(3n + 2) 

This way, it won't matter whether you're using a component-driven approach or not, as you'll be able to alternate the styling directly off of <section> itself.

Elements that inherit an attribute from internal stylesheets (such as <a> tag colour) will unfortunately still be styled based on the internal stylesheet, rather than rules defined by their parent.

You can get around this by either using context-styling:

section:nth-of-type(n) {    background: #464646;    color: #fff;  }    section:nth-of-type(n) a {    color: #fff;  }
<section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>

Or alternatively (and preferably) making use of the inherit value to tell every <a> tag to inherit its color from its parent:

section {    background: #464646;    color: #fff;  }  a {    color: inherit;  }
<section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>

Hope this helps!

Answers 2

In a component based approach the ideal way to do this is to have a mapping ready between backgrounds and foreground colours in your style guide. It should be a one to one mapping that should apply to majority of your elements. Have CSS classes defined for the same.

Next have a wrapper container for all your components. Its purpose is to impart text colours to its wrapped components. So the approach is to have a background colour class for the section and then a foreground colour class for the contents that runs applies to wrapper but runs the style through all the contents.

Note: Specific colour overrides can always reside inside your components file for instance using a highlight on some text etc.

The library that is suggested in the comments does the exact same thing. There is a primary and secondary colour in the theme object. The primary applied to the section and secondary is passed on to the individual components as context. I suggest having it passed only to the components' wrapper.

A somewhat clever way to have classes defined is like

t-wrapper-[colorName] 

Now this can be generic and colorName can come in as a context to your wrapper based on the background color

Hope this helps. Let me know if this answers what you need or you would need supporting snippets for the same.

Answers 3

You can set alternating background styling using nth-child(odd) and nth-child(even) pseudo-classes on <section>:

body{    margin:0;  }  section{      padding:20px;  }  section h2{    margin:0;  }  section:nth-child(odd){    background:#f5f7f6;    color:#333;  }  section:nth-child(even){    background: #113343;    color: #fff;  }
<section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>  <section>      <h2>Title</h2>      <p>Text</p>      <a href="#" class="btn">Action</a>  </section>

Read More

Tuesday, February 7, 2017

How to reference in directory of SCSS file from component?

Leave a Comment

Currently I have the following directory structure:

stylesheets ..modules ...._all.scss ...._colors.scss ..partials ...._all.scss ...._Home.scss ..main.scss 

And in my _Home.scss I have:

@import '../modules/all';  .headerStyle {   color: pink;   font-size: 15;   font-weight: 500; } 

And in my main.scss I import all the _all.scss in stylesheets folder like:

@import 'modules/all' @import 'partials/all'  html { font-family: 'Roboto', sans-serif; } body {   margin: 0;   background-color: orange } 

And lastly in my component, I would import the stylesheet like so:

import '../../stylesheets/main.scss'  ...  <div className="headerStyle">Header</div> 

Yet, the div is not being styled with .headerStyle in _Home.scss. I checked the directory path to main.scss and it is correct, and I'm not getting any errors.

And the following is actually being applied:

body {   margin: 0;   background-color: orange } 

What could I be doing wrong? And is there a better way to import stylesheets into a component rather than having to define it every time for a component?

Thank you in advance and will upvote/accept answer.

4 Answers

Answers 1

I tried the following successfully (using plain HTML and the Scout-App to transform SCSS to CSS):

Edit: As mentioned I've never used React but based on this post hugogiraudel.com it should be the same syntax as in my solution (more or less/on first sight ;-) ).

Edit 2: I started using SCSS just a few days ago myself. As far as I can tell your only errors are the few typo's shown in my example. Since 'body' is applied I assume the import statement in your component is correct for React.

If there is a better solution to do imports into components has to be answered by someone else. But it looks like the author of the linked blog post has another approach and there is also a github repository available.

directory structure:

- project_folder     - index.html     - stylesheets         - main.scss         - partials             - _all.scss             - _Home.scss 

Index.html

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">     <head>         <!-- NOTE: 'css_stylesheets' is the folder where the                     Scout-App added the transformed CSS files -->         <link rel="stylesheet" href="css_stylesheets/main.css" type="text/css" />     </head>     <body>         <!-- NOTE: I don't know anything about React but                     in HTML the attribute is 'class' not 'className'                    Edit 3: 'className' is correct, my bad -->         <div class="headerStyle">Header</div>     </body> </html> 

stylesheets/main.scss

@import 'partials/all'; // Your missing here a semicolon (;) I think  html { font-family: 'Roboto', sans-serif; } body {   margin: 0;   background-color: orange; // here too but wasn't crucial } 

stylesheets/partials/_all.scss

@import '_Home.scss'; 

stylesheets/partials/_Home.scss

.headerStyle {   color: pink;   font-size: 30px; // I added here pixels because Firefox ignored it otherwise   font-weight: 500; } 

Answers 2

You have configured Webpack to use stylesheets directory so you could use

import 'main.scss' 

instead of

import '../../stylesheets/main.scss' 

Answers 3

@fingerpich hit on a good solution for making your paths simpler. You can set up an alias to your stylesheets directory, and then always import relative to that directory:

Webpack config:

{   resolve: {     alias: {       // the path needs to resolve relative to the files where you're importing them       stylesheets: path.resolve(__dirname, '../stylesheets')     }   } } 

Docs: https://webpack.github.io/docs/configuration.html#resolve-alias

Component file:

import 'stylesheets/main.scss' 

Also you can let webpack resolve imports from inside your sass files by adding ~ to the front of the path. Then you can write your imports there just like in your component files and they'll resolve to your alias:

@import '~stylesheets/modules/_colors.scss' 

Docs: https://github.com/jtangelder/sass-loader#imports

Answers 4

In the overall code which you have provided only one thing is missing semi-colon(;) While using SCSS we have to use semi-colon to terminate the statement.

Here is the updated code :

@import 'modules/all'; @import 'partials/all';  html { font-family: 'Roboto', sans-serif; } body {   margin: 0;   background-color: orange; } 
Read More

Sunday, January 8, 2017

Rails: how to check CSS or JS code code from a string?

Leave a Comment

In a code string I have stored a piece of code, can be CSS, SASS, SCSS, JavaScript or CoffeeScript. The content is coming from the user, and I need to validate the syntax before saving in the database.

I need to check if the syntax is correct. Currently, I'm using an ugly hack that works. Do you have a better solution?

def check_js   if language == 'coffee'      # CoffeeScript     CoffeeScript.compile code   else                         # JavaScript     Uglifier.compile code   end rescue ExecJS::RuntimeError => e   errors.add :code, e.message end  def check_css   if language == 'css'         # CSS     Sass::CSS.new(code).render   else                         # SASS, SCSS     Sass.compile code, syntax: language.to_sym   end rescue Sass::SyntaxError => e   errors.add :code, e.message end 

2 Answers

Answers 1

I don't see the code in the question as a hack.

I think if you want something that can really run in the browser, test it in a browser.

Ruby has two excellent ways to run browsers to evaluate code, Capybara and PhantomJS.

Answers 2

Nokogiri is an HTML, XML, SAX, and Reader parser. Among Nokogiri's many features is the ability to search documents via XPath or CSS3 selectors.

Features

  • XML/HTML DOM parser which handles broken HTML
  • XML/HTML SAX parser
  • XML/HTML Push parser
  • XPath 1.0 support for document searching
  • CSS3 selector support for document searching
  • XML/HTML builder
  • XSLT transformer

Nokogiri parses and searches XML/HTML using native libraries (either C or Java, depending on your Ruby), which means it's fast and standards-compliant.

Refer Nokogiri

Read More

Tuesday, August 2, 2016

Webpack - Style sheet loading but no fonts

Leave a Comment

I am able to see my stylesheet in the page without problems. However I cannot get my webfonts to work. I have tried to save the output of my css which doesn't happen. I believe this is why the fonts aren't working.

Webpack

var webpack = require ('webpack'); var ExtractTextPlugin = require('extract-text-webpack-plugin');  module.exports = {      resolve: {         extensions: ['', '.js']     },      entry: ['webpack-hot-middleware/client','./src/client/js/Kindred.js'],      output: {         path: './public',         filename: 'bundle.js',         publicPath: '/public/js'     },      devtool: 'cheap-module-source-map',     module: {         loaders: [             {                 test: /\.js$/,                 exclude: /node_modules/,                 loader: 'babel-loader',                 query: {presets: ['es2015', 'react', 'react-hmre', 'stage-0']}             },             {test: /\.scss$/, loaders: [                 'style?sourceMap&modules',                 'css?sourceMap&modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]',                 'resolve-url',                 'sass?sourceMap&modules']},             { test: /\.css$/, loader: ExtractTextPlugin.extract("style-loader?modules!css-loader?sourceMap&modules" )},             {test: /\.png$/, loader: "url-loader?limit=100000"},             {test: /\.jpg$/, loader: "file-loader"},             {                 test: /\.(eot|svg|ttf|woff|woff2)$/,                 loader: 'file?name=public/font/[name].[ext]'             }         ]     },      sassLoader: {         includePaths: [ 'src/client/scss' ]     },      plugins: process.env.NODE_ENV === 'production' ? [         new ExtractTextPlugin ('app.css', {allChunks: true}),         new webpack.optimize.DedupePlugin (),         new webpack.optimize.OccurrenceOrderPlugin (),         new webpack.optimize.UglifyJsPlugin ()     ] :  [         new webpack.HotModuleReplacementPlugin(),         new webpack.NoErrorsPlugin(),         new ExtractTextPlugin("[name].css")     ]  }; 

Font.scss

@font-face {   font-family: 'fontello';   src: url('/public/font/fontello.eot?42978343');   src: url('/public/font/fontello.eot?42978343#iefix') format('embedded-opentype'),        url('/public/font/fontello.woff2?42978343') format('woff2'),        url('/public/font/fontello.woff?42978343') format('woff'),        url('/public/font/fontello.ttf?42978343') format('truetype'),        url('/public/font/fontello.svg?42978343#fontello') format('svg');   font-weight: normal;   font-style: normal; } 

Build Out

Hash: 6dbe5412ed2de3ad1f84 Version: webpack 1.13.1 Time: 5989ms                                    Asset      Size  Chunks             Chunk Names                                bundle.js    2.2 MB       0  [emitted]  main     0.4dfc2adf9da9e1d82440.hot-update.js    402 kB       0  [emitted]  main     4dfc2adf9da9e1d82440.hot-update.json  36 bytes          [emitted]                              bundle.js.map   2.51 MB       0  [emitted]  main 0.4dfc2adf9da9e1d82440.hot-update.js.map    419 kB       0  [emitted]  main chunk    {0} bundle.js, 0.4dfc2adf9da9e1d82440.hot-update.js, bundle.js.map, 0.4dfc2adf9da9e1d82440.hot-update.js.map (main) 2.08 MB [rendered]   [565] ./~/css-loader?sourceMap&modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!./~/resolve-url-loader!./~/sass-loader?sourceMap&modules!./src/client/scss/main.scss 401 kB {0} [built]      + 565 hidden modules webpack: bundle is now VALID. 

Folder Structure

enter image description here

HTML

<!doctype html public="storage"> <html> <link rel='stylesheet' href='/public/styles.css' type='text/css' /> <title>MyKindred.com</title> <div id=app></div> <script src="/public/js/bundle.js"></script> 

2 Answers

Answers 1

Since Sass doesn't provide url rewriting, using url() is a bit tricky. A simple fix is to use relative paths to the entry file.

@font-face {   font-family: 'fontello';   src: url('../font/fontello.eot?42978343');   src: url('../font/fontello.eot?42978343#iefix') format('embedded-opentype'),        url('../font/fontello.woff2?42978343') format('woff2'),        url('../font/fontello.woff?42978343') format('woff'),        url('../font/fontello.ttf?42978343') format('truetype'),        url('../font/fontello.svg?42978343#fontello') format('svg');   font-weight: normal;   font-style: normal; } 

Answers 2

That's because Sass doesn't have "resolve url" option (But stylus and less(default option) do have it). The only solution I know is to use another loader that will resolve all urls https://github.com/bholloway/resolve-url-loader. Something like:

{    test   : /\.scss$/,    loaders: "!css!resolve-url!sass?sourceMap" }    
Read More

Wednesday, April 20, 2016

Sublime Text 3 with Sass Support

Leave a Comment

Since Bootstrap changed from less to sass... I have to use sass now. I somehow can't find an easy solution for having auto-completion and auto-compiling on save for Sublime Text 3.

Does anyone know a Plugin or something which gives me these features?

I want to be able to specify where the compiled css should go, where my custom-sass files are and where bootstrap is located. :)

Thanks

3 Answers

Answers 1

There are a lot of tools which allow you to build your CSS assets from SASS files (including Bootstrap-SASS).

From Sublime Text:

You can use one of the better I've seen and used: Syntax Highlighting for SASS

I assume you know how to install packages in Sublime (if not, follow this instruction here: https://sublime.wbond.net/installation)

Recommendation:

When working with SASS, I always recommend to use the command-line to compile your SASS (using a Task-Runner like Gulp, Grunt or Webpack). In my daily workflow, I use Gulp, Browsersync and Autoprefixer when working with SASS assets.

Hope that helps!

Answers 2

I'm with @Carlos Bensant about using the command line while working with Sass, and all the task runner he suggests are interesting tools. However, if you don't want to deal with a bunch of extra configuration, that you may don't need, but want to compile Sass to CSS and have all the process control, I'd hardly recommend using Compass. In config.rb file, you set where your Sass, CSS, images and JavaScript files are located, what extensions to require, what syntax you prefer, the output style and much more.

You can also check this fast and easy tutorial for getting started and have everything properly installed :D Compass is really easy to configure and use!

You also have this Sublime Text plugin that seems to work like Compass except for the command line, I personally never used it but I'm going to test it too.

Hope that helps!

Answers 3

I combine the SublimeOnSaveBuild and "Sass Build" packages. This will automatically (assuming you have SASS on your computer) do the build when saving. However, there are no options. It simply builds the css file to the same directory (and with the same filename) as the scss file.

Read More