css - 将小 div 精确定位在大 div 的中心。 CSS中获取div的大小

标签 css css-position

所以,这就是我的 div 的样子(我说的是带有 4 个白色方 block 的蓝色菱形): enter image description here

我想将这个白色方 block 恰好放在其父项两侧的中心。现在他们虽然处于中心位置,但是看起来却相当的奇怪。我应该将它们的位置减少一半左右,但这只能在 CSS 中实现吗?我不想为此使用 JS,因为代码会难以辨认。

CSS

.handle {
    position: absolute;
    width: 1em;
    height: 1em;
    background-color: white;
    border: black 1px solid
}
.handle#top {
    left: 50%;
    top: 0;
}

.handle#left {
    left: 0;
    top: 50%;
}

.handle#right {
    right: 0;
    top: 50%;
}

.handle#bottom {
    left: 50%;
    bottom: 0;
}

HTML

<div class="object">
    <div class="handle" id="left"></div>
    <div class="handle" id="right"></div>
    <div class="handle" id="top"></div>
    <div class="handle" id="bottom"></div>
    <img src="svg/test1.svg" class="stopro"/>
</div>

最佳答案

您有 width: 1em;height: 1em; 所以当您使用 top: 50%;left: 50%; 另外,使用 margin-topmargin-left 扣除边距,它们等于总 height 的 1/2元素的 code> 和 宽度

Demo

Demo 2

.handle#top {
    left: 50%;
    top: 0;
    margin-left: -.5em;
}

.handle#left {
    left: 0;
    top: 50%;
    margin-top: -.5em;
}

.handle#right {
    right: 0;
    top: 50%;
    margin-top: -.5em;
}

.handle#bottom {
    left: 50%;
    bottom: 0;
    margin-left: -.5em;
}

关于css - 将小 div 精确定位在大 div 的中心。 CSS中获取div的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20948860/

相关文章:

javascript - myDiv.style.display 在主样式表中设置时返回空白

html - 如何使用 Bootstrap 行和列增加文本区域的高度

CSS 定位在 Logo 和 <aside> 之间造成丑陋的差距

css - 从不同链接访问博客时按钮位置会发生变化

html - 白边位置:fixed even if margin:0 and padding:0

html - 修复了 100% 宽度的 DIV 覆盖滚动条

css - 需要对多行文本应用相同的左对齐

css - CSS缩进只是为了可读性吗?

javascript - 如何使用 JQuery 将样式应用于正确的标签

css - 固定 thead 的表