Search code examples
htmlcsspositionwidthabsolute

Set absolute positioned element width to its content (it is only a text)


I am going to build this

enter image description here

This is my HTML code

<div class="al-head-container">
    <div></div>
    <span>Center Websites</span>
</div>

This is css :

.al-head-container{
    margin: auto;
    width: 100%;
    padding:0 4%;
    position: relative;   
    box-sizing: border-box;
}

.al-head-container > span{
    font: 2.1em titr;
    color: #ae7f00;
    background-color: #FFFFFF;
    position: absolute;
    right: 0;
    left:0;

}
.al-head-container > div{
    width: 100%;
    height: 20px;
    background-image: url("../image/head-line.jpg");
    position: relative;
    top: 25px;
}

But this is the result of code

enter image description here

The problem is the span width is set to 100% and its width doesn't fit to its content. it is what I get from the firebug

enter image description here

As you see the text covers the DIV that contains the line.

I tried to set the display:inline-block for span but nothing changed. How do I can make the absolute positioned span width to fit the content?


Solution

  • Why not accomplish this purely in CSS with a single element:

    div {
        border-top:1px solid lightgrey;
        border-bottom:3px solid lightgrey;
        height:2px;
        position:relative;
        margin-top:15px;
    }
    div:after {
        content:attr(data-label);
        position:absolute;
        top:-10px;
        left:50%;
        padding:0 20px;
        display:inline-block;
        background:#fff;
        transform: translateX(-50%);
        text-align:center;
        color:#A37716;
        font-size:24px;
    }
    <div data-label="Center Websites"></div>