使绝对定位的伪元素的宽度随着其内容而不是其父元素的宽度而扩展

时间:2018-12-01 09:53:36

标签: html css css3 absolute

现在我必须为伪元素设置一个宽度,但是不同长度的文本需要不同的宽度

默认行为是它随着父级宽度扩展 和我试图避免换行内容

我了解空白:nowrap,但有点像

标记

<section id="mainNav">
    <div>
        <nav><a 
            class="darkBlue" href="www.google.com">
                <span data-hover="aaaa">aaa</span>
            </a><a
            class="grassGreen" href="www.google.com">
                <span data-hover="bbbb">bbb</span>
            </a><a
            class="red" href="www.google.com">
                <span data-hover="cccc">ccc</span>
            </a><a
            class="olive" href="www.google.com">
                <span data-hover="dddd">ddd</span>
            </a><a
            class="orange" href="www.google.com">
                <span data-hover="eeee">eee</span>
            </a><a
            class="oceanBlue" href="www.google.com">
                <span data-hover="ffff">fff</span>
            </a><a
            class="purple" href="www.google.com">
                <span data-hover="gggg">ggg</span>
            </a>
        </nav>
    </div>
</section><!-- //MAIN NAVIGATION// -->

样式

#mainNav {
    width: 100%;
    position: fixed;
    top: 46px;
    z-index: 2;
    height: 48px;
    background-color: #1a1a1a;
    color: #fff;
}
#mainNav > div {
    height: 48px;
    overflow: hidden;
}
#mainNav nav {
    margin-right: 35px;
}
#mainNav nav > a {
    position: relative;
    display: inline-block;
    font: 12px/49px "...";
    margin-right: 35px;
}
#mainNav nav > a:first-child {
    margin-right: 0;
}
#mainNav nav span {
    position: relative;
    display: inline-block;
    transition: transform 0.3s;
    z-index: 1;
}
#mainNav nav > a:hover span {
    transform: translateY(-100%)
}
#mainNav nav span:before {
    position: absolute;
    top: 100%;
    content: attr(data-hover);
    transition: background 0.3s;
    transform: translate3d(0,0,0);
    font-size: 16px;
    font-weight: 700;
}
#mainNav nav > a:hover span:before {
    background-color: transparent !important;
}
#mainNav .darkBlue span:before {
    background-color: #17729a;
    color: #3194bf;
    width: 92px;
    right: -12px;
}
#mainNav .grassGreen span:before {
    background-color: #4caf50;
    color: #4caf50;
    width: 116px;
    right: -15px;
}
#mainNav .red span:before {
    background-color: #e53935;
    color: #e53935;
    width: 74px;
    right: -9px;
}
#mainNav .olive span:before {
    background-color: #b5a92a;
    color: #b5a92a;
    width: 86px;
    right: -10px;
}
#mainNav .orange span:before {
    background-color: #ef6c00;
    color: #ef6c00;
    width: 78px;
    right: -9px;
}
#mainNav .oceanBlue span:before {
    background-color: #00bcd4;
    color: #00bcd4;
    width: 54px;
    right: -7px;
}
#mainNav .purple span:before {
    background-color: #8267ad;
    color: #8267ad;
    width: 73px;
    right: -8px;
}

也在Firefox中,我有一个奇怪的错误,该错误使悬停时的文本 并且当我将px添加到宽度时,它可以解决,但是我正在寻找一种避免完全设置宽度的方法

0 个答案:

没有答案