尝试在我页面的中心对齐html按钮

时间:2012-08-03 15:53:37

标签: html button vertical-alignment alignment

无论使用何种浏览器,我都试图将HTML按钮完全对齐在页面的中心。它可以浮动到左边,同时仍然在垂直中心,或者在页面的某个位置,如页面顶部等。

我希望它可以垂直和水平居中。这是我现在写的:

<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
   mybuttonname
</button> 

9 个答案:

答案 0 :(得分:118)

以下是您的解决方案:JsFiddle

基本上,将按钮放入带居中文字的div中:

<div class="wrapper">
    <button class="button">Button</button>
</div>

使用以下样式:

.wrapper {
    text-align: center;
}

.button {
    position: absolute;
    top: 50%;
}

皮肤猫的方法有很多,而这只是一种。

答案 1 :(得分:49)

通过简单地使用text-align

,您可以在父div上不使用margin:auto; display:block;的情况下居中按钮

例如:

<强> HTML

<div>
  <button>Submit</button>
</div>

<强> CSS

button{
  margin:auto;
  display:block;
}

了解行动: CodePen

答案 2 :(得分:18)

我最近真的对display: table采取了固定大小的事情,例如让margin: 0 auto能够正常工作。让我的生活变得更轻松。你只需要通过&#39; table&#39;显示并不代表表格HTML。

它对于响应式设计特别有用,其中事情变得毛茸茸和疯狂50%离开这个,而-50%变得难以管理。

style
{
   display: table;
   margin: 0 auto
}

JsFiddle

此外,如果您有两个按钮并且您希望它们具有相同的宽度,您甚至不需要知道每个按钮的大小以使它们具有相同的宽度 - 因为该表将神奇地崩溃他们适合你。

enter image description here

JsFiddle

(如果它们内联并且你想将两个按钮并排放在一边 - 这也是有效的 - 尝试用百分比来做!)。

答案 3 :(得分:4)

尝试这很简单,并且让你无法对你的.css文件进行更改,这应该可行

<p align="center">
<button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%"> mybuttonname</button>
</p>

答案 4 :(得分:4)

以下是问题的解决方案

<button type="button" style="background-color:yellow;margin:auto;display:block">mybuttonname</button>

答案 5 :(得分:2)

对我而言,它使用了flexbox。

在父div /元素周围添加一个css类:

.parent {
    display: flex;
}

并使用按钮:

.button {
    justify-content: center;
}

你应该使用父div,否则按钮不会知道&#39;页面/元素的中间是什么。

答案 6 :(得分:2)

有多种方法可以解决此问题。 PFB其中两个-

第一种使用位置的方法:固定-位置:固定;相对于视口的位置,这意味着即使滚动页面,它也始终位于同一位置。将左侧和顶部的值加到50%会将其放置在屏幕中间。

 button {
   position: fixed;
   left: 50%;
   top:50%;
 }

第二种方式使用保证金:自动-保证金:0自动;用于水平居中,但余量:自动;一直拒绝进行垂直居中工作……直到现在!但实际上,绝对居中只需要声明的高度和以下样式即可:

button {
  margin: auto;
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 40px;
}

答案 7 :(得分:1)

将其放在另一个div中,使用CSS将按钮移到中间位置:

<div style="width:100%;height:100%;position:absolute;vertical-align:middle;text-align:center;">
    <button type="button" style="background-color:yellow;margin-left:auto;margin-right:auto;display:block;margin-top:22%;margin-bottom:0%">
mybuttonname</button> 
</div>​

以下是一个示例:JsFiddle

答案 8 :(得分:0)

制作所有宽度为100%,高度为100%的父元素,并使用 display:table; display:table-cell; 检查工作样本。 >

Working Git Version

<!DOCTYPE html>
<html>
<head>
<style>
html,body{height: 100%;}
body{width: 100%;}
</style>
</head>
<body style="display: table; background-color: #ff0000; ">

<div style="display: table-cell; vertical-align: middle; text-align: center;">
    <button type="button" style="text-align: center;" class="btn btn-info">
       Discover More
    </button>
</div>

</body>
</html>