center content uniformly using em's

center content uniformly using em's

本文关键字:em content uniformly using center      更新时间:2023-10-11

我在使用em将自定义单选按钮"tick"居中放置在其父项的中心时遇到问题。

使用px可以很好地工作,但em无法在特定大小下统一居中。它将内容放错了几个像素,有时看起来很随意。例如,如果我在不更改任何样式的情况下重新加载页面,它有时可能会正确呈现,有时则会错误呈现。

下面是一把小提琴,展示了这个问题。(切换ems/像素并更改大小以查看问题)

http://jsfiddle.net/rainerpl/1k35tfgL/

<body>
    <div id="parent">
        <div id="child"></div>
    </div>
    <input type="button" id="toggle" value="toggle em vs px"/>
    <input type="button" id="bigger" value="increace size"/>
    <input type="button" id="smaller" value="decrease size"/>
</body>
body {
    font-size: 10px;
}
#parent {
    width: 32px;
    height: 32px;    
    border: 2px solid rgb(37, 177, 172);
    border-radius: 20px;
    background: white;
    margin: 20px;
}
#child {
    width: 24px;
    height: 24px;
    margin: 4px;
    background: rgb(37, 177, 172);
    border-radius: 10px;
}
#parent.em {
    width: 3em;
    height: 3em;    
    border: 2px solid rgb(37, 177, 172);
    background: white;
    margin: 20px;
    border-radius: 2em;
}
#parent.em #child {
    width: 2em;
    height: 2em;
    margin: 0.46em;
    background: rgb(37, 177, 172);
    border-radius: 2em;
}
var size = 10;
$(document).ready(function() {
    $("input#toggle").click(function() {
        $("#parent").toggleClass("em");
    });
     $("input#bigger").click(function() {
         size++;
         $("body").css("font-size", size);
    });
     $("input#smaller").click(function() {
        if ( size > 1 ) {size--;}
        $("body").css("font-size", size);
    });
});

我能做些什么来保持使用em,并确保它总是均匀显示吗。

如果在我的快速测试中保持圆圈的比例不变,那么您的示例似乎很好。例如,使用基本大小更改.46em to .4em2em to 2.4em3em to 3.4em,这与24px和34px相同。请记住,ems会取整,因为你不能有分数像素。

Fiddle here:http://jsfiddle.net/1k35tfgL/2/