gpt4 book ai didi

html - 用 inline-block 创建完美的正方形

转载 作者:太空宇宙 更新时间:2023-11-04 07:54:29 26 4
gpt4 key购买 nike

我想知道是否有一种方法可以使用 display: inline-block 创建一个完美的正方形,原因是我想将它放在文本旁边,例如

.legend {
display: inline-block;
color: rgba(0, 0, 0, 0);
width: 1em;
background-color: lightblue;
}
<div>
<div class="legend">
d
</div>
<div style="display: inline-block">
Some legend
</div>
</div>

现在它看起来还是有点像矩形。

最佳答案

您也可以简单地指定 div 的高度。请考虑以下事项:

/* The container needs to be relatively positioned */
.container {
position: relative;
}

/* The legend is absolutely positioned, but in relation to its
* container.
* We also apply a common trick to place it at the vertical center of
* its parent: position the top bound at 50% of the parent's height.
* then transform the position to move it up by 50% of its own height.
*/
.legend {
display: inline-block;
color: rgba(0, 0, 0, 0);
width: 1em;
height: 1em;
background-color: lightblue;
position: absolute;
top: 50%;
transform: translateY(-50%);
}

/* This div is decisive for the whole thing's height.
* Since the legend is positioned in an absolute way, we need to make
* room for it by moving this div to the right (margin-left)
*/
.legend-text {
margin-left: 1em;
padding: 5px;
display: inline-block;
}
<div class="container">
<div class="legend">
d
</div>
<div class="legend-text">
Some legend
</div>
</div>

关于html - 用 inline-block 创建完美的正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464794/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com