Gleb Kost Gleb Kost - 1 year ago 91
CSS Question

Child selectors with Glamorous css-in-js

I've trying out the Glamorous library for css-in-js and can not wrap my head around one thing.

With vanilla css you can easily add styles to all selectors within a class, say:

.my-awesome-class div {
margin-right: 10px;
}


Is there any way to achive it with glamorous? For example in this snippet Im looking for a way to state that all the divs inside the container should have a
margin-right
of 20px without the need to pass it to each component:

import React from 'react';
import { render } from 'react-dom';
import glamorous, {Div} from 'glamorous';

const Container = glamorous.div({
display: 'flex'
});

class App extends React.Component {
render() {
return (
<Container>
<Div backgroundColor="tomato" padding="10px">One</Div>
<Div backgroundColor="wheat" padding="10px">Two</Div>
<Div backgroundColor="salmon" padding="10px">Three</Div>
</Container>
);
}
}

render(<App />, document.getElementById('root'));


here's a link to the working snippet:
https://stackblitz.com/edit/glemorouschildselector

Answer Source

glamorous component factory style arguments are powered by glamor which has support for contextual selectors.

contextual selectors: & will be replaced by the 'pointer' to the target rule

const Container = glamorous.div(
    {
        display: 'flex',
        '& div': {
            marginRight: '20px',
        },
    },
)

glamor selector documentation: https://github.com/threepointone/glamor/blob/master/docs/selectors.md

Working demo: https://stackblitz.com/edit/glemorouschildselector-fzj77j

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download