Absolute div 的宽度变得太小以至于文本被换行

Absolute div's width becomes so small that the text is wrapping

当我制作一个按钮时,我想制作一个 div,它会在我将鼠标悬停在按钮上时出现,尽管我对它的宽度和位置有疑问。

问题可以在下面的图片和 jsfiddle 中看到。当我对相对按钮进行绝对设置时,看起来它的最大宽度变成了按钮的宽度。如果按钮很小,悬停 div 也会很小。如何使用 width:auto 进行正常悬停 div?

http://jsfiddle.net/ghpc9fwk/

不确定这是否适合您,但您或许可以使用 ::before 伪元素来实现这种布局。

.alt-test{    
    background-color:blue;    
    display:inline-block;
    margin:0;
    padding:0;
    position:relative;    
    margin-bottom:20px;
}

.alt-test::before{
    content:"";
    display:block;
    height:10px;
    width:10px;
    background:red;
    position:absolute;
    left:0px;
    top:-10px;    
}

JSFIDDLE

只需添加一个 white-space: nowrap; 属性即可防止文本在最近的情况下换行;)

这是一个工作示例:http://jsfiddle.net/1revewwm/

我也修改了bottom属性

是这样的吗?

<div class="button">
    <div class="alt">Click here now!</div>
</div>

.button{
    width:10px;
    height:10px;
    background-color:red;
}
.alt{
    margin-top: 10px;
    display: none;
    background-color:blue;
    width: auto;
    white-space: nowrap;
}

.button:hover .alt{
    display: inline-block;
}

Updated Fiddle

您可以使用 position: relative; 将按钮和替代容器包装在另一个 div 中。 Example fiddle

HTML:

<div class="wrapper">
    <div class="button"></div>
    <div class="alt">Click here now!</div>
</div>

CSS:

.wrapper {
    position: relative;
}

.button{
    width:10px;
    height:10px;
    background-color:red;
    position:relative;
}

.alt{
    position:absolute;
    background-color:blue;
    display: none;
}

.button:hover + .alt {
    display: block;
}

如前所述,一个简单的解决方案是将 white-space:nowrap 添加到您的 alt/caption div,这样它就会一直延伸,直到您插入一些 <br>

另外

我建议你不要使用

bottom: -[something]px

但要使用

top: 100%.

这样按钮的高度就可以变了。

我相应地修改了你的 JSFiddle:http://jsfiddle.net/ghpc9fwk/3/