html - 居中包含左对齐文本的 div + 另一个 div

标签 html css

我正在尝试:

  • 将包含 2 个内联元素的容器 div 居中:另一个 div 和一个标题。
  • 标题可以是任意长度。
  • 元素必须彼此相邻。
  • 文本必须左对齐。
  • div 必须与文本中心垂直对齐。

这是目标:

intention

这就是我目前所拥有的。

HTML

 <div class="container">
  <div class="container">
    <div class="box"></div>
    <h2>This is my title</h2>
  </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis ipsum reprehenderit ipsam hic adipisci ex obcaecati asperiores ab rerum, incidunt eius eligendi ea, odit, maiores fugit cumque modi, facere laudantium.</p>
   <div class="container">
    <div class="box"></div>
    <h2>This is another title. It could be any length. Any length at all.</h2>
  </div>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Officiis ipsum reprehenderit ipsam hic adipisci ex obcaecati asperiores ab rerum, incidunt eius eligendi ea, odit, maiores fugit cumque modi, facere laudantium.</p>
</div>

CSS 。容器{ 宽度:80%; 高度:自动; margin : 0 auto ; 背景色:rgba(150,100,200,0.8); 文本对齐:居中; 填充:1em; p{ 文本对齐:左; }

.box{
  display: inline-block;
  width: 3em; 
  height: 3em;
  background-color: lightblue;
  vertical-align: middle;
}

h2{
  display: inline-block;
  width: calc(100% - 4em);
  margin: 0 auto;
  text-align: left;
}

它在 codepen

非常感谢帮助。

最佳答案

这是一个使用 display: table 的解决方案。

编辑 - 改进

Have a fiddle!

HTML

<div class="container">
    <div class="heading">
        <div class="box">
            <div></div>
        </div>
         <h2>This is my title</h2>    
    </div>
    <p>Content</p>
</div>

CSS

* {
    margin: 0;
    padding: 0;
}
.box {
    display: table-cell;
    vertical-align: middle;
}
.box div {
    width: 3em;
    height: 3em;
    background-color: lightblue;
}
h2 {
    display: table-cell;
    vertical-align: middle;
    padding: 0 0 0 10px;
    text-align: center;
    max-width: 400px;
}
.heading {
    display: table;
    margin: 0 auto;
}
p {
    text-align: center;
}

关于html - 居中包含左对齐文本的 div + 另一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24762323/

相关文章:

css - 如何在 CSS 中使用悬停同时更改两个元素的属性

reflection - 使用-webkit-box-reflect 时如何设置反射的不透明度?

JQuery Mobile - 在显示页面之前调整表单元素的大小

javascript - 如何在 Bootstrap 范围 slider 中添加两个值

html - 0.1 rem border-width 在 chrome 和 safari 上呈现不同

javascript - 如何以 Angular 对html表的每一行进行组件化

javascript - 在具有动态高度的背景图像上创建渐变叠加

android - 为什么我的网站的移动版上有笑脸和空白?

android - 在某些手机中以整页显示的 Jquery 移动应用程序标题

ios - -webkit-溢出-滚动 : touch is not recognized in chrome and on ios