Wouter Vandenputte
Wouter Vandenputte

Reputation: 2093

CSS: set width to width of parent

I am working with an Angular mat-sidenav. On the left I have a navigation and on the right simple comtent.

enter image description here

The place where we see Navigation should have a seperate background-color like the quickly painted image here. So to be 100% clear: I need the div with class nav-title-container to fill the parents width.

enter image description here

Yet when I try to do this, only the few pixels around the text are colored in. Probably because I am doing it wrong. I am also not that familiar with css (it has been quite some years). What simple stuff am I seeing over my head? I pressume the solution is quite simple yet I cannot find it on my own.

HTML

<mat-sidenav-container>
    <mat-sidenav #sidenav mode='side' [(opened)]="opened">
       <div class="nav-title-container">
            <h4 class='nav-title'>Navigation</h4>
        </div>
       ....
</mat-sidenav-container>

CSS

mat-sidenav {
    background-color: lightcoral;
    width: auto;
    padding-left: 5em;
    padding-right: 5em;
}

.nav-title{
    width: 100%;
    
}

.nav-title-container{
    width: max-content; /* I Presume this should be something else, already tried 100% */
    background-color: goldenrod;
    border-bottom: 0.2em solid wheat;
}

Upvotes: 0

Views: 408

Answers (1)

ziale
ziale

Reputation: 111

You probably want to do something like this in your css:

mat-sidenav {
  background-color: lightcoral;
}

.nav-title {
  margin: 0;
  padding: 1.33em 5em;
  cursor: pointer;
}

.nav-title--highlighted {
  background-color: goldenrod;
  border-bottom: 0.2em solid wheat;
}

and this in your html:

    <mat-sidenav ...>
        <h4 class="nav-title nav-title--highlighted">Navigation</h4>
        <h4 class="nav-title">Statistics</h4>
    </mat-sidenav>

h4 will have a 1.33 top and bottom margin unless you reset this with margin: 0. This number appears in the padding to allow you to color the background of the title. In general you want to add the padding on the element you want to see colored, most of the time it is the innermost component (in this case the h4). I added a cursor, you probably want the whole tag to be clickable later.

The containers were not needed.

Try it on Stackblitz

Upvotes: 1

Related Questions