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

标签 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> -->

最佳答案

你不需要高度来集中固定它。只需添加内边距并移除边距,它就会产生您需要的效果。

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

https://jsfiddle.net/dbnrvxkq/

关于html - CSS:具有 flex 边缘和居中文本的 <div>(水平和垂直居中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57484767/

相关文章:

jQuery点击图片并显示一个div

javascript - 如何更改 jQuery UI Draggable 中发生捕捉的距离

javascript - 使用 jQuery,无法将单击行为添加到使用 innerHTML 创建的按钮

jquery - 标题周围不需要的边距

javascript - 为什么 Web 应用程序通过网络发送 HTML?

html - HTML 表单无效时保留所选文件

html - 如何保证网页在不同浏览器中看起来统一?

html - 如何使位于 `<div>` 后面的链接可点击

html - 更改双列表框中单击选项的背景颜色

CSS3 解析错误 词法错误