如何在Bootstrap 4中控制兄弟姐妹的宽度?

时间:2019-07-11 19:32:29

标签: javascript css twitter-bootstrap bootstrap-4

我在<p>元素下面有两个<h1>元素,并且我希望呈现的段落的宽度不要超过标题中内容的90%宽度。 <p><h1>元素的内容是使用Django在服务器端动态生成的,并且也可以包装在较小的屏幕尺寸上。

我尝试d-flexflex-columnflex-shrink时碰碰运气。我能做的最好的事情就是<p>的动态和响应式调整大小,但是我失去了在父容器div中将3个元素水平居中的能力。

<div class="container">
  <div class="text-center">
    <h1 class="display-4">A Short Big Title!</h1>
    <p class="lead">This is a pretty long sentence, and it could be longer than the title above, however, I would not like its width to exceed 90% of that h1 tag above.</p>
    <p><i>This is a shorter sentence, however, I still have the same hopes for its width.</i></p>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

策略1(蓝色):要获取标题下90%的段落,我们首先检查了标题的宽度...即视口宽度的100;这意味着要获得90%的宽度,我们必须在左侧/右侧放置5%(视口宽度的宽度)边距;

策略2(绿色):我们检查了<h1>的渲染宽度,即413px,接下来我们的段落为413px,将边距设置为auto获得漂亮的集中文本;

在下面的代码段中实现的两种解决方案:

.divStrategy1 p {
  margin: 0 5vw;
  color: blue;
}

.divStrategy2 p {
  width: 413px;
  margin: auto;
  color: green;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

<div class="text-center divStrategy1">
  <h1 class="display-4">A Short Big Title!</h1>

  <p class="lead">This is a pretty long sentence, and it could be longer than the title above, however, I would not like its width to exceed 90% of that h1 tag above.</p>

  <p><i>This is a shorter sentence, however, I still have the same hopes for its width.</i></p>
</div>

<div class="text-center divStrategy2">
  <h1 class="display-4">A Short Big Title!</h1>

  <p class="lead">This is a pretty long sentence, and it could be longer than the title above, however, I would not like its width to exceed 90% of that h1 tag above.</p>

  <p><i>This is a shorter sentence, however, I still have the same hopes for its width.</i></p>
</div>