在块级元素的右上角添加按钮

re1*_*man 3 html css

如何在块级元素的右上角添加按钮?可以说我有:

<div>some content here</div>
Run Code Online (Sandbox Code Playgroud)

让我们说这个内容足够长来制作一个“块”,我将如何格式化以在块的右上角有一个按钮,就在块旁边?

MrW*_*ite 9

(1) 一种方法是button在容器顶部浮动右侧。

<div><button>My Button</button>some content here</div>

div + button {
float: right;
}
Run Code Online (Sandbox Code Playgroud)

(2) 另一种方法是将button绝对定位在div容器内并给出div容器位置(以便绝对定位在其中的元素相对于该容器)。这样,按钮可以位于标记中的任何位置,前提是它位于容器内。

div {
position: relative;
}

div button {
position: absolute;
top: 0;
right: 0;
}
Run Code Online (Sandbox Code Playgroud)

但是,该按钮现在将位于容器内的其他内容之上,因此您可能需要使用填充等对其进行调整。