【问题标题】:How to align a button contained within a div central and bottom?如何对齐包含在 div 中心和底部的按钮?
【发布时间】:2018-06-25 09:44:06
【问题描述】:

我使用以下 HTML 代码创建了三个相同的框(除了 p 标签中包含的描述长度),其中包含一个图标、标题、描述和按钮:

    .coursebutton {
    display: inline-block;
    border-radius: 4px;
    background-color: #009ada;
    border: none;
    color: #FFFFFF;
    text-align: center;
    font-family: 'Raleway', sans-serif;
    text-transform: uppercase;
    font-size: 13px;
    padding: 9px;
    width: 100px;
    transition: all 0.5s;
    cursor: pointer;
    }
    <div class="col_one_third col_one_third_even">
    	<div class="feature-box fbox-plain">
    		<div class="fbox-icon">
    			<img src="images/am-icon.png"/>
    		</div>
    		<h3>ADVERTISING AND MEDIA</h3>
    		<p>Example example example example example example example example example example example example </p>
    		<button class="coursebutton" onclick="window.location.href = 'courseinfo/am.html';"><span>Details </span></button>
    	</div>
    </div>

无论 p 元素中有多少文本,如何使按钮始终位于框的底部和中心?

【问题讨论】:

    标签: html css button alignment vertical-alignment


    【解决方案1】:

    只需在您的代码中添加相对位置、50% 的左侧和 -50% 的 translateX。无论文本大小如何,按钮都将始终居中。

    您需要翻译,因为 CSS left 属性基于父元素的大小,而 transform 属性基于目标元素的大小。使用这两种方法,您可以将内容完全集中在它们的父级中。

    .coursebutton {
      display: inline-block;
      border-radius: 4px;
      background-color: #009ada;
      border: none;
      color: #FFFFFF;
      text-align: center;
      font-family: 'Raleway', sans-serif;
      text-transform: uppercase;
      font-size: 13px;
      padding: 9px;
      width: 100px;
      transition: all 0.5s;
      cursor: pointer;
      position: relative;
      left: 50%;
      transform: translateX(-50%);
    }
    

    Example here

    编辑 1

    为了使不同块中的按钮处于同一水平,我们需要块具有相同的高度。为此,我们可以使用类似 javascript equalHeigh 的东西。虽然对我来说最好的选择是使用 flexbox。

    https://jsfiddle.net/uugmvcvm/

    【讨论】:

    • 这非常适合使按钮居中,谢谢!但是,如果其中一个 div 中包含更多文本,则该 div 中的按钮将低于其他按钮。有没有办法让其他按钮也坐这么低?
    • 为了使按钮的高度相同,您需要块的大小相同。而不是使用javascript matchHeight,我更喜欢使用flexbox:link
    【解决方案2】:

    有代码给你。

    总计:

    • 用 DIV 包裹按钮
    • 向父级添加相对和填充
    • 添加 absolute 和 text-align: center 到按钮包装

    Codepen code

    .col_one_third {
      border: 1px solid #ccc;
      text-align: center;
      width: 30%;
      padding-bottom: 40px; // required
      position: relative;   // required
    }
    .button-wrapper {
      position: absolute;   // required
      bottom: 0;            // required
      left: 0;              // required
      text-align: center;   // required
      width: 100%;          // required
      padding: 5px;         // only styling
    }
    

    【讨论】:

      猜你喜欢
      • 2014-04-05
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-24
      • 1970-01-01
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多