使用css`after`

时间:2015-05-04 13:35:13

标签: css css3 flexbox

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

enter image description here

#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;

enter image description here

如何将文字置于边框中间?

此外,如果我尝试使用margin-left/right: auto进行居中,则会将文字放在左下角:

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

enter image description here

2 个答案:

答案 0 :(得分:0)

您可以使用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%;
  }

答案 1 :(得分:0)

你可以试试这个:

#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;
  }