【问题标题】:How to force two inline elements wrap together如何强制两个内联元素包裹在一起
【发布时间】:2018-09-19 14:30:12
【问题描述】:

我有以下问题:这是html:

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

我希望 div 中的两个元素(a 和按钮)始终彼此相邻。

目前,当我更改窗口大小并且两个元素都没有足够的空间时,按钮被包裹,a 在 1. 行,按钮在 2. 我想要的是,文本的一部分(标签 a)也可以用按钮预先包装,所以按钮永远不会单独出现在 2. 行中。

我该怎么做?我一直在玩 white-space:nowrap.. 但还没有成功。

编辑:在 div 上使用 display flex:

我想要什么:

我不想要的:

【问题讨论】:

  • 但是按钮总是位于 2-3-x 行文本旁边。我希望按钮正好位于文本的末尾。例如,它也应该直接位于 1. 文本行的下方。编辑:我编辑了问题
  • @akcasoy 你会制作小提琴吗?
  • 在 div 中添加 flex-wrap: wrap 和 justify-content: space-around
  • @vishugosain 不。也没有意义
  • @NoOorZ24 奇怪地问这个问题.. 但这里是:jsfiddle.net/e6md27n0 您必须更改浏览器大小才能看到问题

标签: html css flexbox


【解决方案1】:

希望这对你有用。

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

【讨论】:

  • 抱歉忘记提了。这是一个有角度的应用程序。链接可能有不同的文本。所以我不知道一个文本可以有多长。我不能改变 html 结构。
【解决方案2】:

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>

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

【讨论】:

    【解决方案3】:

    如果你稍微改变一下结构并wrap最后一个hyperlinked字用button,你就可以做到纯CSS,和display 包装器 元素 作为inline-block:

    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>

    【讨论】:

      猜你喜欢
      • 2019-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多