问题描述
每列包含由图标和文本标签组成的行。
左列的每一行都必须按原样向左对齐。
右列的行必须对齐,使最宽的行接触父容器的右边缘,其他行对齐,以便它们的左边缘对齐,如下图:
我很难理解...我正在考虑将容器的 display
设置为 flex
,将每列的 flex
设置为 1
以便它们' 的宽度相等,然后尝试对右列的行做一些事情,但我不知道是什么。我事先不知道文本标签是什么,但我确信它们的长度可能会有很大差异并且可以换行。包装后是否可以将包装标签向右对齐?
这是我目前拥有的代码 https://jsfiddle.net/t7qksr3g/1/。它基于@Kretiss 的答案,但无法正常工作。当右列中的文本换行时,它不会向右对齐。
我希望有人能帮助我。解决方案可能与我上面描述的完全不同,并不要求行实际上在垂直容器内,我只需要达到视觉效果即可。
更新
我认为如果不使用 JS,我想要实现的目标可能是不可能的,因为浏览器计算容器宽度的逻辑并不能以允许它 CSS Width / Max-Width on Line Wrap? 的方式工作。
解决方法
最后,我找到了解决方案。由于我的原始解决方案已包含在问题中,因此我会将这个答案编辑为新的答案。
这是工作小提琴:https://jsfiddle.net/Kretiss/mbt68qw2/
首先,这是 HTML。将 editWidth
类添加到可能被编辑的段落。
<div class="container">
<div class="column">
<div class="columnChild">
<img src="smile.jpg">
<p class="">Some text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text that wraps because its long long long</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text</p>
</div>
</div>
<div class="column">
<div class="columnChild">
<img src="smile.jpg">
<p>Some longerrrrr text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p>Some text</p>
</div>
<div class="columnChild">
<img src="smile.jpg">
<p class="editWidth">Some text that wraps because its long sad Some text that wraps because its long</p>
</div>
</div>
</div>
CSS 几乎相同。
*{
box-sizing: border-box;
}
.container{
max-width: 500px;
width: 100%;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: flex-start;
border: 2px solid black;
}
.column{
width: fit-content;
width: -moz-fit-content;
width: -webkit-fit-content;
border: 1px solid red;
}
.columnChild{
display: flex;
justify-content:flex-start;
align-items: center;
}
.columnChild img{
height: 50px;
}
这就是魔法。例如,通过此脚本将 JQuery 包含到文件中
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
然后添加此脚本:
<script>
$(document).ready(function(){
$.fn.textWidth = function(){
const html_org = $(this).html();
const html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
const width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
function changeWidth(resizing){
const elements = $(".editWidth");
elements.each(function(index){
if(resizing) $(this).css("width","auto");
const currentWidth = $(this).textWidth();
$(this).css("width",currentWidth + 2);
});
}
changeWidth(false);
$(window).resize(function(){
changeWidth(true);
});
});
</script>
DOM 加载后,一切都以 changeWidth(false);
开头。它使用 false 参数调用 changeWidth(resizing)
函数,因为浏览器窗口没有调整大小。该函数循环遍历所有包含 editWidth
类的段落。在 .each()
函数内部调用 $.fn.textWidth
函数,该函数返回段落内文本的精确宽度。之后,行 $(this).css("width",currentWidth + 2);
将段落宽度设置为文本宽度 + 2px(您可以根据需要进行更改)。
当用户调整浏览器大小时,
$(window).resize(function(){
changeWidth(true);
});
被调用并执行与上述相同的操作。唯一的区别是它首先将段落的宽度设置为自动,否则文本的宽度可能与实际情况不同。
返回文本精确宽度的函数来自这篇文章:Calculating text width