【问题标题】:Center within a border applied to element using css `after`使用css`after`在应用于元素的边框内居中
【发布时间】:2015-05-04 21:58:36
【问题描述】:

我想使用after 创建一个带有文本附加到元素的带边框元素。文本需要在边框内居中,看起来像一个按钮。目前文本位于底部。我尝试使用flex webkit,但它仅将文本水平居中。

#wrapper {
  background-image: none;
  border:1px solid #021a40 !important;
  left: 0px !important;
  top: 115px !important;
  &:after {
    content: 'Some Text';
    display: -webkit-flex;
    display:         flex;
    -webkit-align-items: center;
    align-items: center;
    -webkit-justify-content: center;
    justify-content: center;
  }

如果我在文本所在的after 中添加填充,它会扩展边框...并且不会将文本放在边框的中心:

padding-bottom: 15px;

如何让文本在边框中间居中?


另外,如果我尝试使用margin-left/right: auto 居中,它会将文本放在左下角:

  &:after {
    content: 'Some Text';
    display: block;
    margin-left: auto;
    margin-right: auto;
  }

【问题讨论】:

  • 父元素是固定高度吗?字符串总是固定长度吗?

标签: css flexbox


【解决方案1】:

您可以使用display: table 属性。

但是,如果您有position: absolute,这将不起作用。假设您需要使用它,您必须将您的 #wrapper 包装在另一个包装器中并将定位属性放在那里。

#wrapper {
  display: table;
  background-image: none;
  border:1px solid #021a40 !important;
  left: 0px !important;  <--- you need to declare `position` for these to work
  top: 115px !important;   <--- you need to declare `position` for these to work
  &:after {
    content: 'Some Text';
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    width: 100%;
  }

【讨论】:

    【解决方案2】:

    你可以试试这个:

    #wrapper {
      background-image: none;
      border:1px solid #021a40 !important; 
      position:relative; /*add this*/
      &:after {
        content: 'Some Text';
        position:absolute;
        left:0;
        top:0;
        bottom:0;
        right:0;
        margin:auto;
      }
    

    【讨论】:

      猜你喜欢
      • 2020-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-17
      • 1970-01-01
      相关资源
      最近更新 更多