首页 > 解决方案 > 两个块:一个具有动态宽度,一个与动态一个宽度相同

问题描述

我基本上有一个包含两个块的容器:一个块将具有动态宽度(基于其中的文本),另一个块的宽度应该与动态宽度相同。如果第二个块的宽度比里面的文本大,它必须打破文本以保持与第一个块相同的宽度。

<container>
  <fixed_dynamic>
    Lorem ipsum dolor sit amet
  </fixed_dynamic>
  <samedynamic>
    few words
  </samedynamic>
</container>

我可以通过这种方式实现一些目标:https ://jsfiddle.net/prxus5vm

问题是,如果我尝试在第二个宽度中写一些使 div 拉伸的东西,它不会破坏单词:https ://jsfiddle.net/prxus5vm/1/ 。它应该打破单词并保持第一个块的宽度。

有什么解决办法吗?我正在寻找 CSS 解决方案,希望尽可能避免使用 javascript。

标签: htmlcss

解决方案


如果您尝试使用这些table-layout属性尽可能地缩小父级,那么您会丢失一个小width的设置。

完成此操作后,第一个元素可以是文本块或图像。最后white-space:nowrap可以方便地避免文本换行并设置您要查找的宽度。

div {
  display: inline-table;/*NEEDED          inline for demo it is still using the table-layout */
  width: 1%;            /*NEDEED          or 0 , see it alike a min-width */
  margin:5px                          /* not needed here */
}

div * {
  padding: 0.25em ;                    /* not needed here */
  margin: 0;                           /* not needed here */
}

div h1 {
  background: green;                   /* not needed here */
  white-space: nowrap;  /* NEDEED */
  font-size:1.1rem                     /* not needed here */
}

p {

  background: yellow;                  /* not needed here */

}
<div>
  <h1>
    Lorem ipsum dolor sit amet
  </h1>
  <p>
    more words than fixed dynamic block 
  </p>
</div>

<div>
  <h1>
    A shorter text 
  </h1>
  <p>
    more words than fixed from dynamic block
  </p>
  <p>
    and a few more words
  </p>
</div>

<h1>BUT, there is a disclaimer !</h1>
<div>
  <h1>
    short
  </h1>
  <p>
    here are words that are themselves longer than the reference ....
  </p>
</div>


推荐阅读