Owpur
Owpur

Reputation: 203

Why is my code getting the width of the screen and not the parent?

So, example.. When I hover over my button I want a line to scale from the middle to the edges of the button. But its getting the width of the screen and scaling it to that. Here's an example on JSFiddle, hope this helps!

https://jsfiddle.net/RVKuzmik/kabnL1yw/

<html lang="en">
<head>
</head>
    <body>
        <h1 id="connectbtn">
            test
        </h1>
    </body>
</html>


#connectbtn {
    text-align: center;
    color: red;
}

#connectbtn:before {
    content: "";
    position: absolute;
    width: 100%;
    height: 1%;
    background-color: tomato;
    visibility: hidden;
    transform: scaleX(0);
    transition: all 0.15s ease-in-out 0s;
}

#connectbtn:hover:before {
    visibility: visible;
    transform: scaleX(1);
}

Upvotes: 2

Views: 54

Answers (4)

pavger
pavger

Reputation: 684

Give #connectbtn:before a left: 0; position.

#connectbtn:before {
    content: "";
    position: absolute;
    width: 100%;
    height: 1%;
    background-color: tomato;
    visibility: hidden;
    transform: scaleX(0);
    left: 0;
    transition: all 0.15s ease-in-out 0s;
}

Upvotes: 3

Peter
Peter

Reputation: 1822

The problem is: #connectbtn:before is an inline element, that's why it is start at the same position then text, you need to convert it to a block element.

html, body, h1 {
    margin, 0;
    padding: 0;
}
#connectbtn {
    text-align: center;
    color: red;
    position: relative;
}

#connectbtn:before {
  	content: "";
  	display: block;
  	position: absolute;
  	width: 100%;
  	height: 5px;
  	background-color: tomato;
  	visibility: hidden;
  	transform: scaleX(0);
  	transition: all 0.15s ease-in-out 0s;
}

#connectbtn:hover:before {
  	visibility: visible;
  	transform: scaleX(1);
}
<h1 id="connectbtn">
    test
</h1>

Upvotes: 0

Obsidian Age
Obsidian Age

Reputation: 42304

The secret is in your absolute-positioning with pseudo-elements. Without specifying an offset, the :before gets positioned relative to the element (like with position: relative). You need to specify that the pseudo-element should be moved rather than offset.

To resolve this, you simply need to add left: 0 to #connectbtn:before:

#connectbtn {
  text-align: center;
  color: red;
}

#connectbtn:before {
  content: "";
  position: absolute;
  left: 0;
  width: 100%;
  height: 1%;
  background-color: tomato;
  visibility: hidden;
  transform: scaleX(0);
  transition: all 0.15s ease-in-out 0s;
}

#connectbtn:hover:before {
  visibility: visible;
  transform: scaleX(1);
}
<body>
  <h1 id="connectbtn">
    test
  </h1>
</body>

Hope this helps! :)

Upvotes: 0

Herman Starikov
Herman Starikov

Reputation: 2756

Add following styles to #connectbtn

position: relative;
max-width: 50px;

Upvotes: 0

Related Questions