JPM
JPM

Reputation: 2066

display:none on all but first child element

<p><span>*</span>Here lies a note.</p>

Using CSS, how can I hide (that is, display:none) the text “Here lies a note.” and show just the “*”?

Upvotes: 1

Views: 8077

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240868

Since you can't select text nodes with CSS, one option is to set the font-size of the parent element to 0, which will effectively hide all the text. Then you can reset the text for the desired element.

.target {
  font-size: 0;
}
.target > :first-child {
  font-size: 16px;
}
<p class="target">
  <span>First node</span>
  Second node
  More text nodes...
</p>


Alternatively, you could also utilize the visibility property as well (since you can set a child element to visibility: visible even when the parent element is set to visibility: hidden:

.target {
  visibility: hidden;
}

.target > :first-child {
  visibility: visible;
}
<p class="target">
  <span>First node</span>
  Second node
  More text nodes...
</p>


As a side note, if you want an alternative, you could wrap the text nodes with <span> elements using JavaScript, and then set the display of all the children element that aren't the first child to none using the selector:

.target > :not(:first-child) {
  display: none;
}

Here is a snippet demonstrating this:

var target = document.querySelector('.target');
Array.from(target.childNodes).forEach(function (node, index) {
  if (node.nodeType === 3 && node.nodeValue.trim()) {
    var span = document.createElement('span');
    span.textContent = node.nodeValue;
    target.replaceChild(span, node);
  }
});
.target > :not(:first-child) {
  display: none;
}
<p class="target">
  <span>First node</span>
  Second node
  More text nodes...
</p>


If you're using jQuery, it would be even shorter:

$('.target').contents()
  .filter(function () {
    return this.nodeType === 3 && this.nodeValue.trim();
  }).wrap('<span />');
.target > :not(:first-child) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="target">
  <span>First node</span>
  Second node
  More text nodes...
</p>

Upvotes: 4

Nenad Vracar
Nenad Vracar

Reputation: 122027

You can use visibility to hide parent and show child element.

p {
  visibility: hidden;
}
p > :first-child {
  visibility: visible;
}
<p><span>*</span>Here lies a note.</p>

Upvotes: 0

Related Questions