I have a ul
with a given hover effect using :after
. This works fine, but I want it to start from the middle instead of the left.
My Code:
ul.my-list{ margin: 20px; padding: 0px; width: 200px;}
ul.my-list li{ list-style: none; position: relative; display: inline;}
ul.my-list li a{ color:#333; text-decoration: none;}
ul.my-list li:after{ content: ''; position: absolute; left: 0px; bottom: -2px; width:0px; height: 2px; background: #333; transition: all 0.45s;}
ul.my-list li:hover:after{ width: 100%;}
ul.my-list li a:hover{ text-decoration: none;}
<ul class="my-list">
<li><a href="#">Welcome to my website</a></li>
</ul>
Quick solution:
Move the original position to left:50%
and then, on hover, move it to left:0
.
ul.my-list {
margin: 20px;
padding: 0px;
width: 200px;
}
ul.my-list li {
list-style: none;
position: relative;
display: inline;
}
ul.my-list li a {
color: #333;
text-decoration: none;
}
ul.my-list li:after {
content: '';
position: absolute;
left: 50%;
bottom: -2px;
width: 0px;
height: 2px;
background: #333;
transition: all 0.45s;
}
ul.my-list li:hover:after {
width: 100%;
left: 0;
}
ul.my-list li a:hover {
text-decoration: none;
}
<ul class="my-list">
<li><a href="#">Welcome to my website</a></li>
</ul>
You can simplify your code using background like below
ul.my-list {
margin: 20px;
padding: 0px;
width: 200px;
}
ul.my-list li {
list-style: none;
display: inline-block;
padding-bottom:2px; /*the space for the gradient*/
background: linear-gradient(#333,#333) center bottom; /*OR bottom right OR bottom left*/
background-size: 0% 2px; /*width:0% height:2px*/
background-repeat:no-repeat; /* Don't repeat !!*/
transition: all 0.45s;
}
ul.my-list li a {
color: #333;
text-decoration: none;
}
ul.my-list li:hover {
background-size: 100% 2px; /*width:100% height:2px*/
}
<ul class="my-list">
<li><a href="#">Welcome to my website</a></li>
</ul>
This is simple, you call the element after left 50% that means this it’s the goon left to the middle when you hover the element after the width 100% and left 0, you already added some transition So, it looks middle to left and right. here the code;
ul.my-list{ margin: 20px; padding: 0px; width: 200px;}
ul.my-list li{ list-style: none; position: relative; display: inline;}
ul.my-list li a{ color:#333; text-decoration: none;}
ul.my-list li:after{
content: '';
position: absolute;
left: 50%; /* change this code 0 to 50%*/
bottom: -2px;
width:0px;
height: 2px;
background: #333;
transition: all 0.45s;
}
ul.my-list.rtl li:after { right: 0; left: inherit; }
ul.my-list li:hover:after{ left:0; width: 100%;} /* add poperty left 0 */
ul.my-list li a:hover{ text-decoration: none;}
<ul class="my-list">
<li><a href="#">Welcome to my website</a></li>
</ul>
<h2>left start and end right</h2>
<ul class="my-list rtl">
<li><a href="#">Welcome to my website</a></li>
</ul>
= = =
Thank you
= = =