Issue
I would like to change the color of the text when the string is too long. If a string is too long, it will display '...' at the end with the color red otherwise the color will be black. I am not sure if it is possible to achieve this.
This is my CSS class
textStyle:{
whiteSpace: 'pre-line',
paddingTop:5,
overflow: 'hidden',
'text-overflow': 'ellipsis',
display: '-webkit-box',
'-webkit-line-clamp': 3,
'-webkit-box-orient': 'vertical'
}
My frontend
String testString = "This is a long long text, it will show three dots when it has more than three lines..."
<div className={classes.textStyle}>{testString}</div>
What it does is when the text is more than 3 lines, it will show '... at the end like below
This is a long long text,
it will show three dots when
it has more than three lines...
What I want is the change the whole text to font color to red when the above case happens. However, the above CSS will also change the color of the text when it only has one line
This is a long long text
Solution
It is not possible with css only. It does not know if the text overflows.
With JS maybe you can check if the inner element has less height than the outer
.outer {
white-space: pre-line;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}
<div className="outer"><span className="inner"> ...content </span></div>
The outer element will stop to grow on 3rd line, but the inner one will get all the height of the text. So if outer.offsetHeight < inner.offsetHeight
that means the text overflows. This needs to be checked on resize as well because the element can change its width or height on windows resize
Something like this:
const [overflows, setOverflows] = useState(false)
useEffect(() => {
const outer = ..., inner = ... // get the elements with useRef
const checkOverflow = () => {
setOverflows(outer.offsetHeight < inner.offsetHeight)
}
const observer = new ResizeObserver(checkOverflow)
observer.observe(inner)
checkOverflow()
return () => {
observer.disconnect()
}
}, [])
...
<div className="outer" style={{color: overflows ? 'red' : 'black'}}>
<span className="inner"> ...content </span>
</div>
Answered By - Oktay Yuzcan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.