CSS:<div>具有弯曲的边缘和居中的文本(水平和垂直居中)

时间:2019-08-13 20:17:07

标签: html css

我想要实现如下所示的功能。

在代码中,我使用固定的高度和边距。

在没有固定的高度和边距的情况下如何实现相同的效果? 如何将文字垂直居中?

注意:div之间的白色边框仅用于说明。

enter image description here

代码:

<style>
  .div{
    width:160px;
    height:50px;
    background-color: gray;
    margin-top: 10px;
    margin-bottom: 10px;
    display:inline-block;
    text-align: center;
    font-size: 30px;
  }
  .bg-gray-left{
    border-top-left-radius: 25px;
    border-bottom-left-radius: 25px;
  }
  .bg-gray-middle{
    border-radius:0px;
  }
  .bg-gray-right{
    border-top-right-radius: 25px;
    border-bottom-right-radius: 25px;
  }
  .container{
    border:solid 1px gray;
    width: 485px;
  }
  .div:nth-child(1),.div:nth-child(2){
    border-right-color: white;
    border-right-width: 1px;
    border-right-style: solid
  }
</style>
<!-- <div class="container"> -->
<div class="div bg-gray-left">div 1</div>
<div class="div bg-gray-middle">div 2</div>
<div class="div bg-gray-right">div 3</div>
<!-- </div> -->

3 个答案:

答案 0 :(得分:1)

您不需要高度即可将其固定在中央。只需添加填充并删除边距,即可创建所需的效果。

.div{
    width:160px;
    background-color: gray;
    display:inline-block;
    text-align: center;
    font-size: 30px;
    padding: 10px;
  }

https://jsfiddle.net/dbnrvxkq/

答案 1 :(得分:1)

尝试在这种情况下使用填充。

<style>
  .div{
    width:160px;
    padding: 5px 0;
    background-color: gray;
    display:inline-block;
    text-align: center;
    font-size: 30px;
  }
  .bg-gray-left{
    border-top-left-radius: 25px;
    border-bottom-left-radius: 25px;
  }
  .bg-gray-middle{
    border-radius:0px;
  }
  .bg-gray-right{
    border-top-right-radius: 25px;
    border-bottom-right-radius: 25px;
  }
  .container{
    border:solid 1px gray;
    width: 485px;
  }
  .div:nth-child(1),.div:nth-child(2){
    border-right-color: white;
    border-right-width: 1px;
    border-right-style: solid
  }
</style>
<!-- <div class="container"> -->
<div class="div bg-gray-left">div 1</div>
<div class="div bg-gray-middle">div 2</div>
<div class="div bg-gray-right">div 3</div>
<!-- </div> -->

答案 2 :(得分:0)

填充物很la脚。更改大小,更改多行内容或根本不做任何事情只是时间问题,然后填充将不再能满足您的要求。使用flex center更可靠:

div {
  height: 100px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  background: aliceblue;
}
<div>
  Center anything
</div>

这将要求您将所有项目包装在一个容器中,或者沿单个轴(弹性方向:行或列)工作,但这实际上是使所有内容完全居中的最简单方法。

相关问题