2017-06-16 50 views
1

我正试图实现一个带有标签和图标的自定义按钮。
问题是,如果标签文本太长,它会溢出。
我的目标是使用CSS来使按钮响应,基于标签文本宽度。如何根据标签文本长度来拉伸容器宽度?

这是我管理迄今为止获得:jsFiddle

.btn_container{ 
 
    position: relative; 
 
    background-color: green; 
 
    height: 40px; 
 
    width: 100px; 
 
} 
 

 
.btn_label{ 
 
    position: relative; 
 
    background-color: red; 
 
    width: 70%; 
 
    height: 100%; 
 
    float:left; 
 
} 
 

 
.btn_icon{ 
 
    position: relative; 
 
    background-color: blue; 
 
    width: 30%; 
 
    height: 100%; 
 
    float: right; 
 
} 
 

 
label{ 
 
    position: absolute; 
 
    left: 50%; 
 
    top: 50%; 
 
    transform: translate(-50%, -50%); 
 
}
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/> 
 
<div class="btn_container"> 
 
    <div class="btn_label"> 
 
    <label>Text i want to fit in the div...</label> 
 
    </div> 
 
    <div class="btn_icon"> 
 
    <i class="fa fa-plus"></i> 
 
    </div> 
 
</div>

问题是,如果标签文本溢出,“btn_label”和“btn_container”宽度应根据拉伸到标签文字宽度。

我怎样才能做到呢?

+0

你好。请同时分享CSS代码 –

+0

嘿Timea!你可以提供一个jsfiddle与你的尝试?检查一下属性word-wrap:normal。这可能是黑客攻击。 –

+0

@Remy不要求jsfiddle。 SO在这里有自己的代码片段,这就是OP应该使用的内容 –

回答

3

有与您在小提琴

  1. 如果你想伸展父DIV(.btn_container)共享代码的一些问题,为什么你设置宽度:100px的呢?使用width:auto

  2. 不要使用float:left这会导致要素走出去的文档的默认流的,所以你需要的宽度设置为btn_container,你不想

  3. 如果使用position:absolute在文本上,宽度将不会被其他元素考虑在内。因此,应避免使用的位置是:绝对的,如果你想它的父有宽度取决于它的宽度

看到下面的溶液或jsFiddle片断

.btn_container { 
 
    position: relative; 
 
    background-color: green; 
 
    height: 40px; 
 
    width: auto; 
 
    display: inline-block; 
 
} 
 
.btn_label { 
 
    position: relative; 
 
    background-color: red; 
 
    width: auto; 
 
    height: 100%; 
 
    display: inline-block 
 
} 
 

 
.btn_icon { 
 
    position: relative; 
 
    background-color: blue; 
 
    width: auto; 
 
    height: 100%; 
 
    display: inline-block; 
 
} 
 

 
label {}
<link href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet"/> 
 
<div class="btn_container"> 
 
    <div class="btn_label"> 
 
    <label>Text i want to fit in the div...</label> 
 
    </div> 
 
    <div class="btn_icon"> 
 
    <i class="fa fa-plus">+</i> 
 
    </div> 
 
</div>

+0

非常感谢!这正是我需要的! :) –

+1

@TimeaSorban很高兴我可以帮助:D。不要忘记评估我接受的答案。谢谢 ! :d –

0

你应该做一个用@media分解点(最小宽度或最大宽度)。 在较小的分辨率下制作第二个按钮,并使用较少的文本。

或者使文本溢出:隐藏;和白色空间:nowrap;

你不能让40px的高度,并把大量的文字,在桌面上确定,但在手机上,文本必须去某处或使其隐藏溢出。