Using before and after pseudo-elements on background image

ε祈祈猫儿з 提交于 2019-12-12 12:25:30

问题


I am wanting to construct navigation items from three (background) images, with the first and last a fixed width, and the central a variable width, depending on the width of the text in the nav item. I have been led to believe that using the pseudo elements before and after would be the best method. When I try this though, the main (central) background image for the nav item is overlapping with the before and after background images.

You can see what I mean on this page.

Here is the CSS:

.box {
   background-image: url(nav/images/nav_02.png);
   background-repeat: repeat;
   height:20px;
   position: absolute;
   padding: 10px 13px;
}


.box:before {
    left: 0;
    background-image: url(nav/images/nav_01.png);
}

.box:after {
    right: 0;
    background-image: url(nav/images/nav_03.png);
}

.box:before,
.box:after {
    content: ' ';
    width: 13px;
    height:40px;
    position: absolute;
    top: 0;
    background-repeat: no-repeat
}

And the HTML:

<div class="box">here is some text</div>

Can I use background-images in this way using pseudo elements?

Thanks,

Nick


回答1:


Yes, but you will have to use left and right attributes for moving the pseudo elements in the right position. padding is not correct for the main box to position. Better use margin.

.box {
    background-repeat-x: repeat;
    background-image: url(nav/images/nav_02.png);
    background-repeat: repeat;
    height: 40px;
    position: absolute;
    margin: 0 13px;
    line-height: 40px;
}

.box:before, .box:after {
    content: ' ';
    display:block;
    width: 13px;
    height: 40px;
    position: absolute;
    top: 0;
    background-repeat: no-repeat;
}

.box:before {
    left: -13px;
    background-image: url(nav/images/nav_01.png);
}

.box:after {
    right: -13px;
    background-image: url(nav/images/nav_03.png);
}


来源:https://stackoverflow.com/questions/10871333/using-before-and-after-pseudo-elements-on-background-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!