Basj
Basj

Reputation: 46453

How to avoid that an <a> with display:block takes whole width?

I'm creating a button in its own line thanks to display: block. But why does it take the whole width? How to make it take the normal width of the text inside the button instead?

html, body { width: 100%; height: 100%; }
#a { width: 100%; height: 100%; background-color: red; }
#b { background-color: blue; display: block; }
<div id="a">
<div>This is a button in its own line, thanks to "display: block"</div>
<a id="b">Button</a>
<div>Something else</div>
</div>

Upvotes: 0

Views: 1490

Answers (2)

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18123

A block element by default takes the full width it's parent. So, instead, use inline-block

html,
body {
  width: 100%;
  height: 100%;
}

#a {
  width: 100%;
  height: 100%;
  background-color: red;
}

#b {
  background-color: blue;
  display: inline-block;
}
<div id="a">
  <div>This is a button in its own line, thanks to "display: block"</div>
  <a id="b">Button</a>
  <div>Something else</div>
</div>

Upvotes: 2

N. Ivanov
N. Ivanov

Reputation: 1823

Give it a display:inline-block; and it will behave as you wish.

Working example

html,
body {
  width: 100%;
  height: 100%;
}

#a {
  width: 100%;
  height: 100%;
  background-color: red;
}

#b {
  background-color: blue;
  display: inline-block;
}
<div id="a">
  <div>This is a button in its own line, thanks to "display: block"</div>
  <a id="b">Button</a>
  <div>Something else</div>
</div>

Upvotes: 2

Related Questions