更改大小时将HTML浮动元素保留在适当的位置

时间:2018-07-29 17:41:02

标签: html css css-float

我不知道如何将元素固定在适当的位置。 当我将鼠标悬停在浮动元素上时,会调整边框,但这会推挤其他元素(图像为300x300px)。如何将它们固定在适当的位置?预先感谢。

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>These are images</h1>
    <div id="container">
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>

        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
    </div>    
</body>
</html>

style.css文件为:

.imgDiv {
float:left;
border: 1px solid black;
text-align:center;
border-radius:10px;
margin: 0px 10px 10px 0px;
} 
.img {
border-radius:10px;
} 
.imgDiv:hover {
border: 5px solid black;
}

2 个答案:

答案 0 :(得分:0)

在悬停时减小边距以保持DIV的位置。

.imgDiv {
  float:left;
  border: 1px solid black;
  text-align:center;
  border-radius:10px;
  margin: 5px;
}
.img {
  border-radius:10px;
} 
.imgDiv:hover {
  border: 5px solid black;
  margin: 1px;
}
<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>These are images</h1>
    <div id="container">
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>

        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
        <div class="imgDiv">
            <img class="img"/>
            <h3>Click on image!</h3>
        </div>
    </div>    
</body>
</html>

答案 1 :(得分:-1)

将此行添加到.imgDive:hover

margin: -4px 6px 10px -4px !important;