如何强制两个内联元素一起换行

3

I have the following problem: This is the html:

<div>
    <a href="x">Link text can also be long</a>
    <button class="xx"></button>
</div>

我希望在div中,a和button两个元素始终相邻。

目前情况是,当我改变窗口大小后,如果没有足够的空间容纳这两个元素,button就会被换行,a在第一行,button在第二行。我希望的是,a元素的部分文本也可以和button一起自动换行,这样button永远不会单独出现在第二行。

我该怎么做呢?我已经尝试了white-space:nowrap,但是还没有成功。

编辑:在div上使用display:flex:

enter image description here

我想要的效果:

enter image description here

我不想要的效果:

enter image description here


但是按钮总是位于2-3行文本的旁边。我想将按钮放置在文本的末尾。例如,它应该直接位于第一行文本下面。编辑:我修改了问题。 - akcasoy
@akcasoy 你能创建一个fiddle吗? - NoOorZ24
将 flex-wrap: wrap 和 justify-content: space-around 添加到 div 中。 - vishugosain
@vishugosain 不对。也没有意义。 - akcasoy
@NoOorZ24 有点奇怪要求一个小提琴来解决这个问题...但是这里有链接:https://jsfiddle.net/e6md27n0/ 你需要改变浏览器大小才能看到问题。 - akcasoy
根据您的需求,jsfiddle运行良好。 - vishugosain
3个回答

1

如果你稍微改变结构,并用button将最后一个超链接词包裹起来,然后将wrapper元素的display设置为inline-block,你就可以纯粹使用CSS实现它。

button {border-radius: 50%}

div {
  width: 350px;
  border: 1px solid;
  animation: width 3s linear infinite alternate;
}

.common {display: inline-block}

@keyframes width {
  to {width: 100px}
}
<div>
  <a href="x">Yes this is a very long text but it </a>
  <span class="common"><a href="x">helps</a> <button class="xx">i</button></span>
</div>


0
希望这对你有用。

a span{
  display: inline-block;
}
<a href="x">Link text can also be <span>long <button class="xx">i</button></span></a>


抱歉,我忘了提到这是一个Angular应用程序,并且链接可能具有不同的文本。因此,我不知道文本可以有多长。我不能太多地更改HTML结构。 - akcasoy

0

你不能仅使用纯粹的 css 来实现,所以必须借助 javascript 的帮助。

.spanWrap { display: inline-block; }

a { text-decoration: none; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div>
  <a href="x">Link text can also be long Link text can also be Link text can also be long Link text can also be</a>
  <button class="xx">Button</button>
  <script type="text/javascript">
    $(document).ready(function(){
      var copyStr = $('a[href=x]').text();
      var tempStr = copyStr.substring(0, copyStr.lastIndexOf(" "));
      var last_word_arr = copyStr.split(" ");
      var last_word = last_word_arr[last_word_arr.length - 1];
      $('a[href=x]').text(tempStr);
      $('.xx').wrap('<span class="spanWrap"><a href="x">' + last_word +' </a></span>');
    })    
  </script>
</div>

注意:调整浏览器大小并查看结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接