html - 如何使用 css 将此按钮设置为 x 轴的中心?

标签 html css

我尝试使用 css 将此按钮设置为 x 轴的中心,但它不起作用。

我该怎么做?

https://jsfiddle.net/9e9rb6L5/

这是html代码。

<div class="one">
    <div class="two">start now</div>    
</div>

这是 css。

.one{
    height: 66px;
    line-height: 36px;
    text-align: center;
    margin: 0 auto;
}
.two{
    float: left;
    background-color: #3498db;
    color: white;
    font-size: 24px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    padding-right: 20px;
}

最佳答案

试试这个: 您需要在 .one 类中添加 width: fit-content;

.one{
    height: 66px;
    line-height: 36px;
    display:block;
  margin:0 auto;
       width: fit-content;
  text-align:center;
}
.two{
    float: left;
    background-color: #3498db;
    color: white;
    font-size: 24px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    padding-right: 20px;
  
}
<div class="one">
    <div class="two">start now</div>    
</div>

  1. 另一种方式:display:table in .one class

.one{
    height: 66px;
    line-height: 36px;
    display:table;
    margin:0 auto;
    text-align:center;
  
}
.two{
    float: left;
    background-color: #3498db;
    color: white;
    font-size: 24px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    padding-right: 20px;
  
}
<div class="one">
    <div class="two">start now</div>    
</div>

  1. 您可以使用 flex 属性的第三种方式。

.one{
    height: 66px;
    line-height: 36px;
    text-align: center;
    margin: 0 auto;
    display:flex;
    justify-content:center;
}
.two{
    float: left;
    background-color: #3498db;
    color: white;
    font-size: 24px;
    padding-top: 15px;
    padding-bottom: 15px;
    padding-left: 20px;
    padding-right: 20px;
}
<div class="one">
    <div class="two">start now</div>    
</div>

关于html - 如何使用 css 将此按钮设置为 x 轴的中心?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46441632/

相关文章:

javascript - 这个语法正确吗

html - 如何使用 Bulma 的默认 $ 变量

javascript - 印地语字体的 chrome 渲染问题

jquery - 淡入 SVG 背景图像

javascript - 我可以将变量分配为数组值吗?

html - 包裹元素上的 CSS 容器宽度

javascript - HTML/JS : How to change option value of select type using JS

div下的CSS div

html - 什么是最好的方法或测试网站兼容性

javascript - 视差 'background-image/position/attachment' jQuery 动画抖动