首页 > 解决方案 > 左对齐和居中对齐 div

问题描述

我想左对齐图像并居中对齐 div 中的文本。

但我得到:

在此处输入图像描述

文本“This is not centered”未完全居中。

HTML如下:

<div id='heading'>
    <div id='heading-inner-container'>
        <img id='logo' src='abc.jpg'/>
        <div id='title'>
            This is not centered
        </div>
    </div>
</div>

和 CSS:

#heading {
    box-shadow: rgba(0, 0, 0, 0.075) 0px 0px 4px 0px;
    box-sizing: border-box;             
    display: flex;
    height: 72px;
    width: 100%;                
    align-items: center;
    border-bottom: 1px solid rgb(222, 226, 230);                
    margin: 0px 0px 16px;               
    padding: 16px 24px;
}
#heading-inner-container {
    width:90%;
    text-align: center;
    margin: 0 auto;
}
#logo {
    float: left;
    height: 60px;
}           
#title {
    font-size: 3.5rem;
    font-weight: 300;
    line-height: 1.2;
    font: normal normal 300 normal 36px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}

我怎样才能使文本准确居中?

标签: htmlcss

解决方案


尝试使用transform规则:

CSS

#heading {
    position: relative; // Add this
    box-shadow: rgba(0, 0, 0, 0.075) 0px 0px 4px 0px;
    box-sizing: border-box;             
    display: flex;
    height: 72px;
    width: 100%;                
    align-items: center;
    border-bottom: 1px solid rgb(222, 226, 230);                
    margin: 0px 0px 16px;               
    padding: 16px 24px;
}


#title {
  display: inline-block;
  position: absolute;
  left: 50%;
  top: 50%;
  white-space: nowrap;
  transform: translate(-50%,-50%);
  font-size: 3.5rem;
  font-weight: 300;
  line-height: 1.2;
  font: normal normal 300 normal 36px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
}

在这里演示


推荐阅读