小编典典

使伸缩容器采用内容的宽度,而不是宽度的100%

css

在下面的示例中,我有一个具有以下样式的按钮…

.button-flexbox-approach {
    /* other button styles */
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1.5rem 2rem;
}

但是它会自动缩放到100%,而不是内容的宽度。您可以设置一个明确的宽度,但是那样一来您的文本就不能自然地换行。

如何制作一个内部文本以flexbox居中但不能增长到适合容器大小的按钮?

.container {

  width: 100%;

  height: 100%;

}



.button {

/*   Simply flexing the button makes it grow to the size of the container... How do we make it only the size of the content inside it? */

  display: flex;

  justify-content: center;

  align-items: center;

  -webkit-appearance: none;

  border-radius: 0;

  border-style: solid;

  border-width: 0;

  cursor: pointer;

  font-weight: normal;

  line-height: normal;

  margin: 0;

  position: relative;

  text-align: center;

  text-decoration: none;

  padding: 1rem 2rem 1.0625rem 2rem;

  font-size: 1rem;

  background-color: #D60C8B;

  border-color: #ab0a6f;

  color: #fff;

}



.one {

  margin-bottom: 1rem;

}



.two {

/* You can put an explicit width on that, but then you lose the flexibility with the content inside */

  width: 250px;

}


<div class="container">

  <p>

    Button one is flexed with no width and it grows to the size of its container

  </p>

  <p>

    <a class="button one" href="#">Button</a>

  </p>

  <p>

    Button two is flexed with an explicit width which makes it smaller, but we have no flexibility for changing the content

  </p>

  <p>

    <a class="button two" href="#">Button 2</a>

  </p>

</div>

阅读 170

收藏
2020-05-16

共1个答案

小编典典

而不是display: flex使用容器display: inline-flex

这会将容器从块级(占用其父级的整个宽度)切换到内联级(占用其内容的宽度)。

这上浆行为类似于display: block对比display: inline-block

2020-05-16