css hide text node but show its children

2019-09-14 17:35发布

问题:

I have html and css selectors as below. I'd like to hide the text node but leave its children. ie. the text node "Dashboard"

<li>
    <a href="#">
        <span class="icon">
          <i class="fa fa-home"></i>
        </span>
        Dashboard  
    </a>
</li>

css

li > a > :not(span){
  display: none;
}

回答1:

Here's a CSS-only example using text-indent to hide the text but keep elements inside visible. This doesn't require you to modify your HTML at all.

/* icon styles just for example: */

.icon {
  background: green;
  display: inline-block;
  height: 15px;
  width: 15px;
  border-radius: 50%;
}

/* hiding happens here: */

a {
  display: block;
  position: relative;
  text-indent: -9999px;
}

a > * {
  position: absolute;
  top: 0;
  left: 0;
  text-indent: 0;
}
<ul>
  <li>
    <a href="#">
      <span class="icon"><i class="fa fa-home"></i></span>
      Dashboard
    </a>
  </li>
</ul>



回答2:

CSS selectors can only select elements (or pseudo-elements), not contiguous text.

But if you want something like display: none, you can use font-size: 0, and restore the desired value on the children elements.

@import 'http://fontawesome.io/assets/font-awesome/css/font-awesome.css';
li > a {
  font-size: 0;
}
li > a > * {
  font-size: 1rem;
}
<li>
  <a href="#">
    <span class="icon">
      <i class="fa fa-home"></i>
    </span>
    Dashboard  
  </a>
</li>

There is also visibility: hidden, which will hide the text but following contents won't move to take the freed space.

@import 'http://fontawesome.io/assets/font-awesome/css/font-awesome.css';
li > a {
  visibility: hidden;
}
li > a > * {
  visibility: visible;
}
<li>
  <a href="#">
    <span class="icon">
      <i class="fa fa-home"></i>
    </span>
    Dashboard  
  </a>
  Following text
</li>



回答3:

CSS cannot access stray text nodes, the ideal solution would be wrapping the text inside a <span> with specific class for hiding, for example:

<span class="link-text">Dashboard</span>

then hiding with CSS:

li > a > .link-text {
  display: none;
}

However, if you cannot modify the HTML, you can try another technique which "clips" the text with overflow: hidden while adding fixed height/width to your container/link:

li > a {
  width: 20px;
  height: 20px;
  overflow: hidden;
  display: block;
}


标签: css css3 sass