简体   繁体   中英

CSS Pseudo-classes with inline styles in react.js

Now example text with the background will be red color. But I want the class rightElement: after having border-top: color. It should take from const. I don't know how to do that

   const color = "red";

   <div className='rightElement' style={{backgroundColor: color} >Example </div>
   rightElement:after

   {
        border-top :color ( From const color )
   }

you looking for this : ? ( https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_custom_properties )

 :root { --my-color: red; } .rightElement { display: inline-block; border-top :5px solid var(--my-color); } 
 <div class="rightElement" > Example </div> 

See CSS pseudo elements in React . It seems that a best practice is to use separate elements in React instead of pseudo-elements. Could you just do this instead?

<div className='rightElement' style={{backgroundColor: color}}>
  Example
  <div style={{borderTopColor: color}}></div>
</div>

It is not possible to directly access the pseudo element.

However, you could change their style indirectly by adding in a new style element containing new rules.

Try like this to add after css.

 const color = "red"; var styleElem = document.head.appendChild(document.createElement("style")); styleElem.innerHTML = "#rightElement:after {border-top: 1px solid "+color+";}"; 
 <div id='rightElement' style="background-color: green" >Example </div> 

In HTML & CSS

 .testAfter::after { content: "->" } 
 <div class="testAfter">Something</div> 

We can use ::after and other pseudo code like this in css.

So we need external css to use pseudo code in react.

// test.css

 .rightElement::after { content: "-> after"; border-top: 1px solid red; } 

// Test.js

 import React from 'react'; import './test.css'; class Test extends React.Component { render () { const color = "red"; return( <div> <div className='rightElement' style={{backgroundColor: color}} >Example </div> </div> ) } } export default Test; 

Using Inline

 render () { const color = "red"; return( <div style={{width: '500px', margin: '0 auto', marginTop: '100px'}}> <div className='rightElement' style={{backgroundColor: color}} >Example </div> <div style={{borderTop: `10px solid ${color}`}}></div> </div> ) } 

The trick here is instant of creating new element via ::after or ::before I create new element by my own. But creating new element for only styling purpose is not good(Just my option).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM