Paragraph Tag forces parent to take full width of

2020-03-24 10:55发布

I am trying to create a very simple layout where a heading, paragraph and button are aligned to the center of the page horizontally and vertically. I want the .centered-div to take the width of the .heading.

Trouble is the paragraph tag seems to break the whole thing by making the .centered-div take the width of the .container instead of the width of the .heading.

If I remove the paragraph .centered-div takes it's maximum width to be the width of the .heading.

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.centered-div {
  display: flex;
  margin: auto;
  align-self: center;
  align-items: flex-end;
  flex-direction: column;
}

.heading {
  display: inline-block;
  text-align: right;
}

.description {
  display: inline-block;
  width: 50%;
}

.link-button {
  width: auto;
}
<div class="container">
  <div class="centered-div">
    <h1 class="heading">A Considerably Long Heading</h1>
    <p class="description">
      Lorem ipsum dolor...
    </p>
    <a class="button" href="/">Learn More</a>
  </div>
</div>

In grey is the .container and the red outline is the .centered-div

The output with the paragraph tag the output without the paragraph tag

If more information is needed please let me know. Thanks in advance for your help.

标签: css
1条回答
家丑人穷心不美
2楼-- · 2020-03-24 11:50

You can use the trick width:0;min-width:100%; with the text container which will allow it to follow the width of the header:

.container {
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
}

.centered-div {
  display: flex;
  margin: auto;
  align-self: center;
  align-items: flex-end;
  flex-direction: column;
}

.heading {
  text-align: right;
}

.description {
  width:0;
  min-width:100%;
  text-align:justify;
}

.link-button {
  width: auto;
}
<div class="container">
  <div class="centered-div">
    <h1 class="heading">A Considerably Long Heading</h1>
    <p class="description">
      Lorem ipsum dolor Lorem ipsum dolorLorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor Lorem ipsum dolor 
    </p>
    <a class="button" href="/">Learn More</a>
  </div>
</div>

查看更多
登录 后发表回答