扩展时固定元素位置

3
有两个盒子(Box1Box2),当我使用Margins和Paddings悬停在其上时,它们会扩展。它们分别拥有自定义类和设计。它们都向左浮动,以便彼此并排。
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>

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
}

我遇到的问题是当鼠标悬停在Box1上时,第二个盒子会稍微向右移动,而当鼠标悬停在Box2上时,第一个盒子不会移动。我不希望在悬停Box1时移动Box2
您可在此处查看 jsfiddle Demo:https://jsfiddle.net/shahrozasif1/7cjm23uj/1/

无法访问您的fiddle。 - smrubin
3个回答

2

消除悬停时的移动的一种方法是在方框上使用 position:absolute

像这样

.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;}

这个答案可能是正确的,但Position:absolute并不总是值得的。例如:如果我想为我的段落添加更多文本,那么ContentBoxes会成为干扰。因此,我很可能更喜欢下面的答案。 - Shahroz Asif

1

:hover上使用负的margin-right:-25px

演示

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

1

我认为这不是行内盒子的最佳方式,但是使用您的代码可以实现此目的:

1)将填充更改为偶数(padding: 74px而不是padding 73px) 2)然后,在.contentbox-lg:hover中添加margin-right:-27px;

也就是说:

.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 */
}

不需要将“Padding”更改为“74px”,您也可以将“Margin-Right”更改为“-25px”,但两者都是正确的。 - Shahroz Asif

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接