2017-08-08 83 views
2

給定以下HTML,是否可以使用CSS選擇器來定位標籤中的文本?使用CSS選擇器來定位html標籤文本

<fieldset class="sl"> 
    <legend> 
     Text Inputs 
    </legend> 
    <label> 
     Text Input: 
     <input type="text" /> 
    </label> 

    <label> 
     Read-only Text Input: 
     <input type="text" readonly value="this is read-only" /> 
    </label> 
</fieldset> 

所以在上面的,我想要的目標「文本輸入」或「只讀文本輸入:」並設置寬度靠左位置文本框。

我能想到的唯一的作品就是將文本包裝在一個範圍內。

<label> 
    <span>Text Input:</span> 
    <input type="text" /> 
</label> 

隨着CSS選擇:

fieldset.sl label span { 
    width: 200px; 
    display: inline-block; 
} 

FYI - 我在看使用CSS在同一行和單獨的行輸入上述標籤之間切換具有兩全其美 - ,而不必修改html結構 - 只對fieldset類進行調整,就像使用span中包裝的標籤中的文本一樣。

Target achieve

回答

3

不幸的是,唯一的CSS屬性,讓你的風格的純文本大多涉及到font manipulation, color and letter spacing

你有幾個最佳實踐解決方案來實現你想要的。

  • 您可以在一個<span>
  • 包裝每個文字或者你可以使用更清潔的替代方案是使用<label>標籤包裹的實際標籤和使用the for attribute<label>元素把它與它的具體input字段。

對於第二個例子中,代替具有這樣的:

<label> 
    <span>Text Input:</span> 
    <input type="text" /> 
</label> 

你將結束了這樣的:

<label for="textinput">Text Input:</label> 
<input type="text" id="textinput" /> 

如果仍然希望組的每個input與其相應<label>和保持對字段組的完全控制,您始終可以將它們包裝在<div>標籤中,如下所示:

<div class="field-group"> 
    <label for="textinput">Text Input:</label> 
    <input type="text" id="textinput" /> 
</div> 
1

您可以在此處使用CSS Grid Layout並使label成爲網格容器。這種方式label的文本將被包裹在匿名網格項中。

CSS grid specs

被直接包含在grid container內文本的每一連續運行被包裹在一個匿名grid item。但是,僅包含white space的匿名網格項目未呈現,就好像它是display: none

演示:

.sl label { 
 
    display: flex; 
 
} 
 

 
.sl label { 
 
    display: grid; 
 
    grid-template-columns: 200px 1fr; 
 
}
<fieldset class="sl"> 
 
    <legend> 
 
    Text Inputs 
 
    </legend> 
 
    <label> 
 
    Text Input: 
 
    <input type="text" /> 
 
    </label> 
 

 
    <label> 
 
    Read-only Text Input: 
 
    <input type="text" readonly value="this is read-only" /> 
 
    </label> 
 
</fieldset>