BlakeWebb
BlakeWebb

Reputation: 533

Add border to element while keeping parent element the same height

I'm looking to add a border to an element on hover while also keeping the parent div size the same.

Currently when I add the border it makes the parent div larger in height.

nav {
  margin: 0px auto 1px auto;
  padding-bottom: 1px;
  display: inline-block;
  position: fixed;
  background-color: #000;
  width: 100%;
}
nav a {
  padding: 10px;
  float: left;
  font-size: 20px;
  background-color: #000000;
  color: white;
  text-decoration: none;
  box-sizing: border-box;
}
nav a:first-child {
  margin-left: 25px;
}
nav a:hover {
  background-color: red;
  border-left: 1px white solid;
  border-right: 1px white solid;
  border-bottom: 1px white solid;
}
<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="http://www.google.com">Google</a>
</nav>

Upvotes: 2

Views: 110

Answers (2)

Jacob G
Jacob G

Reputation: 14172

There are a couple of ways to do it.

Method No. 1 - Give the <a> a transparent border:

nav a {
  padding: 10px;
  float: left;
  font-size: 20px;
  background-color: #000000;
  color: white;
  text-decoration: none;
  box-sizing: border-box;
  border-left: 1px transparent solid;
  border-right: 1px transparent solid;
  border-bottom: 1px transparent solid;
}

Method No. 2 - Give the <nav> a fixed height:

nav{
height:45px;
}

Upvotes: 2

Josh Crozier
Josh Crozier

Reputation: 240958

You could add a transparent border to displace the one that is added on hover.

In this case, you could use:

nav a {
  border: 1px transparent solid;
  border-top: none;
}

nav {
  margin: 0px auto 1px auto;
  padding-bottom: 1px;
  display: inline-block;
  position: fixed;
  background-color: #000;
  width: 100%;
}
nav a {
  padding: 10px;
  float: left;
  font-size: 20px;
  background-color: #000000;
  color: white;
  text-decoration: none;
  box-sizing: border-box;
  border: 1px transparent solid;
  border-top: none;
}
nav a:first-child {
  margin-left: 25px;
}
nav a:hover {
  background-color: red;
  border: 1px white solid;
  border-top: none;
}
<nav>
  <a href="#">Home</a>
  <a href="#">About</a>
  <a href="http://www.google.com">Google</a>
</nav>

Upvotes: 2

Related Questions