如果可以在发生自动换行时调整div元素的大小。为了演示,请使用类似问题中的fiddle:
<div class="mypost">
<div class="test">I represent the imagdfv fdvdsdfsdfve.</div>
</div>
CSS:
.mypost {
border: 1px solid Peru;
margin: auto;
min-width: 200px;
display: inline-block;
background: red;
}
.test {
margin: 10px;
background: cyan;
}
如果你要让窗口变小以便发生换行,你会发现右边有一个蓝色的空白区域。当换行发生时,我希望蓝色减少直到它到达第一行的最后一个字母。
这可能吗?
答案 0 :(得分:1)
我认为这可能是不可能的。我做了一些搜索,我发现了这个重复的问题,但是这个问题没有解决方案:How to remove extra space caused by word-wrap in shrunk to fit element?
这是我尝试的东西可能接近你想要的东西。基本上我只是内联.test
。我将填充物移动到容器中。
.mypost {
border: 1px solid Peru;
margin: auto;
min-width: 200px;
width:300px;
display: inline-block;
background: red;
font-size:18px;
line-height:20px;
padding:10px;
}
.test {
margin:0;
background: cyan;
display:inline;
position: relative;
}
<div class="mypost">
<div class="test" contenteditable="true">
EDIT ME..... Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</div>
</div>
答案 1 :(得分:0)
tl;博士:没有。
一旦发生自动换行,包含文本的块级元素被认为尽可能宽,以填充其容器,无论文本在何处断开。
可以使用javascript查找起始高度的最小宽度框,但由于重复重绘而且这对CSS不太友好,因此效率低下:
target = document.getElementsByClassName('test')[0];
height = target.clientHeight;
minWidth = 1;
maxWidth = target.clientWidth;
while(maxWidth - minWidth > 1) {
var newWidth = (minWidth + maxWidth) / 2;
target.style.width = newWidth + "px";
if(target.clientHeight > height) {
minWidth = newWidth;
}
else {
maxWidth = newWidth;
}
}
target.style.width = maxWidth + "px";
.mypost {
border: 1px solid Peru;
margin: auto;
width: 200px;
display: inline-block;
background: red;
}
.test {
margin: 10px;
background: cyan;
}
<div class="mypost">
<div class="test">I represent the imagdfv fdvdsdfsdfve.</div>
</div>
答案 2 :(得分:0)
对我来说,我会做内在的div display: inline-block;
所以:
.mypost {
border: 1px solid Peru;
margin: auto;
min-width: 200px;
display: inline-block;
background: red;
}
.test {
display: inline-block;
margin: 10px;
background: cyan;
}
<div class="mypost">
<div class="test">I represent the imagdfv<br/>fdvdsdfsdfve.</div>
</div>