2016-02-13 109 views
3

我無法獲得一個contentEditable元素來顯示爲一個固定的框(例如2個字符寬)。因爲它只是填充的寬度。在框中有文本時工作正常,但我希望有一個具有特定寬度的空框。有任何想法嗎?如何設置html內容固定寬度的可編輯div

HTML:

<!DOCTYPE html> 
<head> 
<link rel="stylesheet" href="so.css" /> 
<body> 
<h1 id="prompt">Type something in the box:</h1> 
<h1 id="textarea"></h1> 
</body> 

CSS:

#prompt, #textarea{ 
    display:inline; 
} 

#textarea{ 
    contentEditable: true; 
    width: 2em; /* 20px doesn't work either */ 
    cursor: text; 
    background-color:rgba(132, 225, 132, 0.9); 
    border: 1px solid black; 
    padding: 2px; 
} 
+1

,評估您的H1,使用任何顯示,但內聯,或浮起來。位置:固定/絕對將允許您調整它的大小。只有**內聯不會允許**它:) –

回答

4

首先,您必須將contentEditable="true"設置爲HTML作爲屬性。

您可以使用Flexbox的並設置min-width#textareaflex-shrink: 0;#prompt。所以#textarea會增長,但不會推#prompt

.content { 
 
    display: flex; 
 
} 
 

 
#prompt { 
 
    flex-shrink: 0; 
 
} 
 

 
#textarea { 
 
    min-width: 100px; 
 
    word-break: break-all; 
 
    cursor: text; 
 
    background-color:rgba(132, 225, 132, 0.9); 
 
    border: 1px solid black; 
 
}
<div class="content"> 
 
    <h1 id="prompt">Type something in the box:</h1> 
 
    <h1 contentEditable="true" id="textarea"></h1> 
 
</div>

+0

對於此問題的其他人,請添加flex-basis:2em; (例如)textarea屬性也可以用來控制它的特定寬度。 –

1

內聯元件不能有寬度或高度。你應該試着讓它們至少是內聯塊。

+0

我試圖通過添加顯示:塊到#prompt,#texarea {..}風格。結果是textarea放在提示符下面的行上。任何方式保持相同的路線? –

+0

@DonSmythe,再讀一遍:) ...內聯塊不阻止! –