在 fieldset 元素的右上角定位图标,并带有相应的标题。

5
我遇到了一个问题,就是下面的布局在所有浏览器中都无法显示相同的效果:

.wrapper {
  margin-top: 100px;
  position: relative;
  height: 400px;
  width: 400px;
  border: 1px solid black;
}

.icon {
  position: absolute;
  width: 40;
  height: 40px;
  border: 1px solid black;
  background-color: white;
  top: -20px;
  right: 10px;
}
<fieldset class="wrapper">
  <legend>Legendary!</legend>
  <div class="icon">icon</div>
</fieldset>

问题在于当legend元素存在时,在Firefox上,div.icon会向下拉动几个像素,在Chrome上则会向上拉动几个像素。当我移除legend元素时,一切都正常了,但我不能这么做。有什么办法使它在所有浏览器中看起来都一样吗?

不确定是否是问题的根源,但您的HTML标记无效。您正在尝试使用div标签关闭fieldset。 - David Jones
这不是问题的根源 :). 这只是我的笔误。它在原始代码中不存在,但为了清晰起见,我会编辑我的问题。 - Marek M.
4个回答

1

这里有一个已更新的工作链接:jsfiddle,已在Chrome和Firefox中测试通过。 您不需要使用position:absolute;,只需将您的div float:right;并给出margin-top:-40px;或您想要的任何值即可。

 #wrapper{
         margin-top: 100px;
         position: relative;
         height: 400px;
         width: 400px;
         border: 1px solid black; 
    }

#icon{
 float:right;   
    background-color:#fff;
    width:40px;
    height:40px;
    border:1px solid black;
    margin-top:-20px;
    margin-right:20px
}
legend#title {
    margin-left: 20px;
    float: left;
    padding-left: 10px;
    margin-top: -10px;
    background: #f3f5f6;
    width: 74px;
}

解决了问题后,你能解释一下为什么这样解决了问题吗?这样,我们所有人都可以从你的答案中学到一些有用的东西,可能适用于未来的其他问题。 - David Thomas
我猜这个不会是响应式的,而你在问题中提到你需要它。 - jarvo69
@sumitbadaya 如果他所有的值都是以像素为单位固定的,那么它怎么可能是响应式的呢? - Edison Biba
那就是我说的。他提到了“在各个地方看起来元素相同”。这也应该包括响应式,但他接受了这个答案,所以想知道如果它不具备响应性,它怎么能成为一个被接受的答案!!! - jarvo69
不知道你们有没有在“移动”视图下测试过它,但它足够响应,意味着两个元素保持在同一位置并保留相同的边距(我不希望这些边距在移动设备上发生任何改变)。 - Marek M.
显示剩余2条评论

0
 .icon {
           float: right;
           margin-top: -30px;
            width: 40px;
            height: 40px;
            border: 1px solid black;
            background-color: white;


        } 

已在Chrome和Mozilla上进行了测试。


1
但问题是在Chrome和Firefox下呈现它。不用担心Edge :) - Marek M.
尝试想出一些新的东西。如果还有错误,请原谅。 - Sazz

-1
尝试以百分比%的形式给出top值。
.icon {
                position: absolute;
                width: 40;
                height: 40px;
                border: 1px solid black;
                background-color: white;
                top: -2.5%;
                right: 10px;
            }  

在这里试验: https://jsfiddle.net/37y8023g/


将 top 属性从像素(px)更改为百分比(percent)没有改变任何内容。 - Marek M.

-1

使用 line-height 来设置 .icon 的样式

CSS:

.wrapper {
    margin-top: 100px;
    position: relative;
    height: 400px;
    width: 400px;
    border: 1px solid black;
}            
.icon {
    position: absolute;
    width: 40;
    height: 40px;
    border: 1px solid black;
    background-color: white;
    top: -20px;
    right: 10px;
    line-height: 40px;
}

工作示例:https://jsfiddle.net/qjqv43y4/1/


这也没有改变任何东西。只需在FF和Chrome下运行它-你就会看到。 - Marek M.

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