Shahroz Asif
Shahroz Asif

Reputation: 143

Fix positions of elements when expanded

There are two boxes (Box1, Box2) which expand when I hover on using Margins and Paddings. They are given custom classes and designs. They both Float left so that they can be next to each other.

The HTML:

<div class="contentbox-lg stk-left bg-red">
  <p class="contentbox-content">Box1</p>
</div>
<div class="contentbox-lg stk-left bg-blue">
  <p class="contentbox-content">Box2</p>
</div>

The CSS:

/* Content Box Main CSS */

.contentbox-lg {
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  padding: 50px;
  width: 50px;
  height: 50px;
  margin-left: 50px;
  margin-top: 50px;
}

.contentbox-lg:hover {
  border: 3px;
  border-style: solid;
  border-color: black;
  padding: 73px;
  margin-left: 25px;
  margin-top: 25px;
}

.contentbox-content {
  top: 50%;
  left: 50%;
  color: white;
}

.stk-left {
  float: left;
}


/* Content Box Colors */

.bg-blue {
  background-color: #2980b9;
}

.bg-blue:hover {
  background-color: #3498db
}

.bg-red {
  background-color: #c0392b;
}

.bg-red:hover {
  background-color: #e74c3c
}

The problem which makes me suffer from is when Box1 is hovered on, the second box slightly moves towards the right and when Box2 is hovered, the first box doesn't move. I don't want Box2 to move when Box1 is being hovered on.

Find jsfiddle Demo here

Upvotes: 3

Views: 54

Answers (3)

Joan Galm&#233;s Riera
Joan Galm&#233;s Riera

Reputation: 593

I don't think that this is the best way to inline boxes, but with your code you can do this:

1) Change your padding to even number (padding: 74px instead padding 73px) 2) Then, you just add margin-right: -27px; inside .contentbox-lg:hover

That is:

.contentbox-lg:hover {
  border: 3px;
  border-style: solid;
  border-color: black;
  padding: 74px; /* change to 74px */
  margin-left: 25px;
  margin-top: 25px;
  margin-right: -27px; /* add this line */
}

Upvotes: 1

Miro
Miro

Reputation: 8650

Use negative margin-right:-25px on the :hover

Demo

.contentbox-lg:hover {
  border: 3px;
  border-style: solid;
  border-color: black;
  padding: 73px;
  margin-left: 25px;
  margin-top: 25px;
  margin-right:-25px;
}

Upvotes: 1

Nutshell
Nutshell

Reputation: 8537

One way to get rid of the movement on hover is to use position:absolute on the boxes

Like this

.contentbox-lg {
  position: absolute;
  border: 1px;
  border-style: solid;
  border-radius: 5px;
  padding: 50px;
  width: 50px;
  height: 50px;
  margin-left: 50px;
  margin-top: 50px;
}

.contentbox-lg { left: 200px;}
.contentbox-lg:first-child { left: 0;}

Upvotes: 2

Related Questions