Jitender
Jitender

Reputation: 7969

Bottom div alignment issue if upper have boder on hover

The issue when adding border property on hover the below div alignment is getting distorted. I know it is because it increase the height of hovered div which cause. Is there any work around.

The box height is depend on content inside it so we cant fix it. fiddle

.col {
  width: 20%;
  padding: 10px;
  float: left;
  box-sizing: border-box
}

.col:hover {
  border: solid 1px red
}
<div>
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
  <div class="col">4</div>
  <div class="col">5</div>
  <div class="col">6</div>
  <div class="col">7</div>
  <div class="col">8</div>
</div>

Edit

I have added the hover property to top most parent div which add transparent border to all the div. which fix this issue but it does not seem good approach because user can see something moving when hover

Upvotes: 0

Views: 55

Answers (4)

Pete
Pete

Reputation: 58462

I would use flex instead of float:

.flex {
    display:flex;        /* make parent flex */
    flex-direction: row; /* make children align in a row */
    flex-wrap:wrap;      /* allow row to wrap if it reaches end */
}

.col {
  flex-basis:20%;               /* this is like width, you could use width but I like to use basis */
  padding: 10px;
  box-sizing: border-box;
  border:1px solid transparent; /* start with this so you don't get any movement on hover */
}

.col:hover {
  border-color: red;
}
<div class="flex">
  <div class="col">1</div>
  <div class="col">2</div>
  <div class="col">3</div>
  <div class="col">4</div>
  <div class="col">5</div>
  <div class="col">6</div>
  <div class="col">7</div>
  <div class="col">8</div>
</div>

More information about flex

Upvotes: 1

Arun
Arun

Reputation: 1185

Don't worry

It is easy, you can use outline:1px solid red;insted of border

That is because , You have given 20% width for each column, totally 5 divs can fit on screen. Once you hover you are adding a border. it will increase width 20%+border width. since you are getting this issue.

See fiddle link https://jsfiddle.net/nmxzzvk5/7/

Upvotes: 1

Clams Are Great
Clams Are Great

Reputation: 280

When you add a border of 1px the padding increase by 1px also. You need to account for this and change the padding to 9px when hovered.

Fixed fiddle: https://jsfiddle.net/nmxzzvk5/4/

.col{width: 20%; padding: 10px; float: left; box-sizing: border-box}
.col:hover{ border: solid 1px red; padding: 9px;}

Upvotes: 1

Supraja Ganji
Supraja Ganji

Reputation: 1207

Add transparent border to child divs and change color of border on hover

  .col {  width: 20%;  padding: 10px;  float: left;  box-sizing: border-box;border: solid 1px transparent;}.col:hover {  border-color: red;}

Upvotes: 0

Related Questions