Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In CSS use "display:none" on the element, but keep its ":after"

Tags:

css

Is it possible to not display an element, as with display:none, but continue to display the :before and/or :after?

I tried

#myspan       {display:none} #myspan:after {display:inline; content:"*"} 

but that didn't work. I'm trying to have CSS replace the content of a span with an asterisk, without introducing jQuery.

like image 932
JPM Avatar asked Dec 27 '12 04:12

JPM


People also ask

How do you hide an element but its position should be left blank?

Look, instead of using visibility: hidden; use display: none; . The first option will hide but still takes space and the second option will hide and doesn't take any space.

How do I show display none in CSS?

getElementById("element"). style. display = "none"; To show an element, set the style display property to “block”.

Which CSS style will remove the element but will keep its space on the website?

The visibility: hidden rule, on the other hand, hides an element, but the element will still take up space on the web page. If you want to hide an element but keep that element's space on the web page, using the visibility: hidden; rule is best.

What does display none do in CSS?

display: none; is commonly used with JavaScript to hide and show elements without deleting and recreating them.


2 Answers

No, it is not possible.

Pseudo elements are rendered like children:

<span id="myspan">whatever<after></span> 

And display:none hides the element including all children.

EDIT 1

JavaScript is your best option in my opinion. Even without jQuery changing text is not hard:

document.getElementById("myspan").innerHTML = "*";​ 

Demo

EDIT 2

However, if you really want to do it with CSS, you can use negative text-indent to hide the text and relative positioning to show the asterisk:

#myspan {         text-indent: -9999px;     display: block; }  #myspan:before {     content: '*';     position: absolute;     top: 0;     left: 9999px; } 

Demo

like image 129
bookcasey Avatar answered Sep 22 '22 14:09

bookcasey


I think a very easy approach to doing this is to exploit the visibility property. But note that a "hidden" element still takes up the space. But if you are okay with that, just make make the parent element "hidden" and pseudo element "visible":

#myspan        {visibility:hidden} #myspan: after {visibility:visible} 

Once you have the visibility taken care of, feel free to play around with the position so that excess space is avoided.

Something like,

myspan {     visibility: hidden;     position: relative; }  myspan:after {     visibility: visible;     position: absolute;     left: 10px; } 
like image 44
PiyushW Avatar answered Sep 20 '22 14:09

PiyushW