css - 如何在CSS中针对内部内容使用 block 的宽度

标签 css

我有一个父 div,其中有两个 div,一个是图像,一个是描述,如下图所示

enter image description here

父 div 具有属性text-align: center。所以它的工作正常,文本图像和描述位于中心。

描述 div 有一个属性max-width: 580px。因此,如果描述文本增加,图像将略微向左移动,如下图所示 enter image description here

而且看起来不错。但是当有一些不适合当前行的长词时,它会使用整个 580px 宽度 并且长词会进入下一行,如下所示

enter image description here

由于使用了整个描述宽度,因此图像通过使用父属性 text-align: center 向左移动。

但它看起来不太好,因为它在 css 逻辑的中心而不是在外观上。

有没有办法只在有内容的时候才占整个宽度

我使用了属性 display: table-caption 现在它只需要文本宽度 enter image description here

它位于父 div 的中心。

但随后它将 Assistant Manager 分成两行,如下所示,我不想要

enter image description here

有没有办法通过一些 css 属性来实现上述任务,或者我必须使用 javascript 来实现上述任务。

最佳答案

由于您没有提供任何代码,我只能猜测。

这是我想出的:https://jsfiddle.net/9888d4tf/1/

HTML

<div class="headline-wrapper">
    <img class="headline-image" src="http://kcdn.at/company/84085/1073352/logo-fairmoney-clever-consulting-gmbh.companybig.gif">
    <p class="headline-title">
        <span>
            Assistant&nbsp;Manager someveryverylonglongtexttext
        </span>
    </p>
</div>

<br/><br/>

<div class="headline-wrapper">
    <img class="headline-image" src="http://kcdn.at/company/84085/1073352/logo-fairmoney-clever-consulting-gmbh.companybig.gif">
    <p class="headline-title">
        <span>
            Assistant&nbsp;Manager
        </span>
    </p>
</div>

CSS

.headline-wrapper {
    background: #fff;
    text-align: center;

    display: flex;
    flex-wrap: nowrap;
    justify-content: center;
}

.headline-wrapper > .headline-image {
    width: 298px;
    height: 92px;
    align-self: center;
}
.headline-wrapper > .headline-title {
    font: 30px/1.1 Verdana;
    display: inline-block;
    text-align: left;
}
.headline-wrapper > .headline-title > span {
    display: table-caption;
}

结果 result of https://jsfiddle.net/9888d4tf/1/


关键是,您之前需要知道哪些词是您不想换行的。然后,您可以将它们包裹在 white-space:nowrap 范围内,或者像我一样用   替换它们之间的空格。

关于css - 如何在CSS中针对内部内容使用 block 的宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38713061/

相关文章:

html - flex 元素不考虑边距和框大小 : border-box

CSS float 和响应行为

css - Yahoo Pure CSS 中的媒体查询

javascript - 以声明方式创建 dojo 按钮

html - 在 CSS 中覆盖以前的背景

css - 如何在 Dojo DataGrid 中增加/减小字体大小

javascript - 播放视频时调暗屏幕的缓和过渡效果

html - 如何在放下显示 :inline? 的同时将 H1 与边框居中

html - 属性溢出不起作用(仅在 div 中设置滚动)

html - css - 如果行数不同则 block 失控