2016-05-31 57 views
4

我針對一個頁面的結構如何定位文本節點?

<div class="x"> 
    <span>This should be visible</span> 
    <span>This should be visible</span> 
    This shouldn't be. 
</div> 

這不是一個網頁我自己,所以我不能改變結構或添加標籤。我只是在製作自定義樣式表,我只能使用CSS。

我首先想到的是嘗試

div.x { display: none; } 
div.x span { display: inline; } 

但這似乎只是隱藏整個元素不管。

+0

你只希望隱藏不應該是可見的(或)你會想做些別的事情與它的內容? – Harry

+0

這是一個標籤內*「這不應該。」*或如同普通 – T04435

回答

4

使用visibility屬性:

一種方法來隱藏元素的文本節點的內容是設置visibility: hiddendiv,然後重寫它的span

使用visibility: hidden的缺點是,如果在文本節點之後有任何其他元素(請參閱下面的代碼段),它會留下空白區域。

div.x { 
 
    visibility: hidden; 
 
} 
 
div.x span { 
 
    visibility: visible; 
 
}
<div class="x"> 
 
    <span>This should be visible</span> 
 
    <span>This should be visible</span> 
 
    This shouldn't be. 
 
    <span>Some other tag</span> 
 
</div>


使用font-size屬性:

其他的辦法是設置font-size: 0px父,然後重寫它的span

這種方法的缺點是你需要知道什麼是子元素的font-size

div.x { 
 
    font-size: 0px; 
 
} 
 
div.x span { 
 
    font-size: 16px; 
 
}
<div class="x"> 
 
    <span>This should be visible</span> 
 
    <span>This should be visible</span> 
 
    This shouldn't be. 
 
    <span>Some other tag</span> 
 
</div>


使用color屬性:

還有一個辦法是設置color: transparent(如Paran0a指出)爲母公司,然後覆蓋它span

不利的一面是,你需要知道子元素的顏色是什麼,文本會佔據空間,因爲它仍然存在,但只有顏色透明(請參閱下面的代碼片段)。

div.x { 
 
    color: transparent; 
 
} 
 
div.x span { 
 
    color: black; 
 
}
<div class="x"> 
 
    <span>This should be visible</span> 
 
    <span>This should be visible</span> 
 
    This shouldn't be. 
 
    <span>Some other tag</span> 
 
</div>

+1

可以將顏色設置爲透明也可以工作嗎? – Paran0a

+1

是@Paran0a。它可以工作,但它會像'可見度:隱藏的',因爲文本仍然佔據空間。 – Harry

+1

上帝該死!我只是寫了一個類似的答案,只是現在堆棧更新了頁面,告訴我還有另一個答案。 +1 xD – Ruddy