Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting css with nested classes to styled components problem

I'm having problems understanding nesting in styled components, i have a code i need to implement in my project but i don't fully understand how to write the same stuff with styled-comp. due to nesting of classes..

CSS:

#cf {
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;
}

#cf img {
  position:absolute;
  left:0;
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

#cf img.top:hover {
  opacity:0;
}

HTML:

<div id="cf">
  <img class="bottom" src="/images/Cirques.jpg" />
  <img class="top" src="/images/Clown%20Fish.jpg" />
</div>

I've been using styled-components for couple of weeks, so i understand the basics, i'm just having problems writing 2 nested objects like it's shown in css...

If u got time to explain it a bit, would be great :)

like image 881
Filip Strelec Avatar asked Apr 29 '19 15:04

Filip Strelec


People also ask

Can I use CSS with styled-components?

You can use standard CSS properties, and styled components will add vendor prefixes should they be needed. Styled components are independent of each other, and you do not have to worry about their names because the library handles that for you.

What problem does styled-components solve?

Advantages of using Styled-components Eliminates class name bugs: styled-components provide unique class names for your styles, thus eliminating the problems with class names duplications, misspellings, and overlaps.

Is styled-components better than CSS?

No class name bugs: styled-components generates unique class names for your styles. You never have to worry about duplication, overlap or misspellings. Easier deletion of CSS: it can be hard to know whether a class name is used somewhere in your codebase.

Is it good to use styled-components?

Styled components are a good choice for building a UI library since everything can be in one file and easily be exported and reused. If you prefer writing pure CSS, use CSS modules. You can have separate CSS files, and it locally scopes styles by default.


1 Answers

it becomes:

import Styled from 'styled-components';

const MyDiv = Styled.div`
  position:relative;
  height:281px;
  width:450px;
  margin:0 auto;

  img {
    position:absolute;
    left:0;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
    transition: opacity 1s ease-in-out;

    &.top:hover{
       opacity:0;
    }
  }
`

 Render

<MyDiv />

Working example

https://codesandbox.io/s/xj3y2qz87q

like image 66
Mosè Raguzzini Avatar answered Sep 30 '22 11:09

Mosè Raguzzini