创建 HTML
- 使用 id 为“wrapper”的 <div>。
- 添加一个类型为“button”的 <button> 。
<div id="wrapper"> <button type="button">onitroad</button> </div>
让我们从创建 HTML 开始。
添加 CSS
- 设置包装器的宽度、高度和边框属性。
- 指定按钮的高度、宽度、顶部和左侧属性。
- 将位置设置为“相对”以相对于其正常位置放置按钮。
- 向按钮添加边距。
#wrapper {
width: 100%;
height: 400px;
border: 2px solid #000;
}
button {
height: 20px;
position: relative;
margin: -20px -50px;
width: 100px;
top: 50%;
left: 50%;
}
让我们看看我们的代码的结果。
在 <div> 中居中按钮的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
#wrapper {
width: 100%;
height: 400px;
border: 2px solid #000;
}
button {
height: 20px;
position: relative;
margin: -20px -50px;
width: 100px;
top: 50%;
left: 50%;
}
</style>
</head>
<body>
<div id="wrapper">
<button type="button">onitroad</button>
</div>
</body>
</html>
接下来,我们来看一个例子,我们使用Flexbox来实现我们想要的效果。
使用 Flexbox 使 <div> 中的按钮居中的示例:
<!DOCTYPE html>
<html>
<head>
<title>文档的标题</title>
<style>
#wrapper {
width: 100%;
height: 300px;
border: 2px solid #000;
display: flex;
align-items: center;
justify-content: center;
}
button {
height: 30px;
width: 90px;
}
</style>
</head>
<body>
<div id="wrapper">
<button type="button">onitroad</button>
</div>
</body>
</html>
在上面的例子中,我们将显示设置为“flex”,然后将 align-items 和 justify-content 的值指定为“center”。
日期:2020-06-02 22:14:58 来源:oir作者:oir
