Home > Enterprise >  Why is the width of element different outside a flex container?
Why is the width of element different outside a flex container?

Time:09-06

Example:

* {
  margin: 0;
  box-sizing: border-box;
}

.row{
  width: 100%;
  height: 90px;
  
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  
  padding: 0 50px;
  
  background-color: grey;
}

a{
  background-color: black;
  color: white;
  width: 8rem;
  text-align: center;
  line-height: 40px;
}
<div >
  <p>Other content</p>
  <a>Test Button</a>
</div>

 <a>Test Button</a>

As you can see, the style of the two anchor tags are not the same. Inside the flex container, the link has the desired width and line-height, but outside it only changes its background color. I guess that has something to do with the container, but I can't tell what. Why is that happening?

CodePudding user response:

From the specification:

The display value of a flex item is blockified: if the specified display of an in-flow child of an element generating a flex container is an inline-level value, it computes to its block-level equivalent.

Your link is an inline element but inside a flexbox container it becomes a flex item and behave differently.

Many properties can do the same like for example using float

a {
  background-color: black;
  color: white;
  width: 8rem;
  text-align: center;
  line-height: 40px;
}
<a>Test Button</a>
<hr>
<a style="float:left">Test Button</a>

width and line-height don't behave the same with inline element or "block-like" elements which explain the difference.

10.3.1 Inline, non-replaced elements

The 'width' property does not apply ref

and

On a non-replaced inline element, 'line-height' specifies the height that is used in the calculation of the line box height. ref

So the width doesn't apply and the line-height won't change the height of the element but is only considered to calculate the line box height.

The trivial fix is to use inline-block

* {
  margin: 0;
  box-sizing: border-box;
}

.row {
  width: 100%;
  height: 90px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 50px;
  background-color: grey;
}

a {
  background-color: black;
  color: white;
  width: 8rem;
  text-align: center;
  line-height: 40px;
  display: inline-block;
}
<div >
  <p>Other content</p>
  <a>Test Button</a>
</div>

<a>Test Button</a>

CodePudding user response:

first of all you have to add display property in anchor tag then only you can add width and height.

a {
    background-color: black;
    color: white;
    width: 8rem;
    text-align: center;
    line-height: 40px;
    display: inline-block;
}
  • Related