I am going to build this
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
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
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?
An absolutely positioned element is an element whose computed position value is absolute or fixed . The top , right , bottom , and left properties specify offsets from the edges of the element's containing block. (The containing block is the ancestor relative to which the element is positioned.)
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
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>
I will suggest make a few changes on your code.
You can remove the div
element and instead use a pseudo-element
later with CSS
<div class="al-head-container">
<span>Center Websites</span>
</div>
Then with CSS make the pseudo-element be the absolute one to place it behind the span:
.al-head-container{
position:relative;
}
.al-head-container > span{
font: 2.1em titr;
position:relative;
z-index:10;
display:inline-block;
padding:0 20px;
height:2.1em;
line-height:2.1em;
color: #ae7f00;
background-color: #FFFFFF;
}
.al-head-container:after{
content:"";
width: 100%;
top:50%;
transform:translateY(-50%);
border-top:dotted 3px red;
position: absolute;
left:0;
}
Check this Demo on Jsfiddle
Note that you can replace the border on the fiddle with your background image
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With