I have a div with some sub divs that I use as tabs, and my parent div has horizontal scroll (i use this for mobile view so width is smaller). Something like this:
.parent {
display: flex;
overflow-x: auto;
padding: 15px 0 20px;
}
.tab {
font-size: 15px;
text-transform: uppercase;
padding: 10px 40px;
color: #a4b5bf;
white-space: nowrap;
}
<div class="parent">
<div class="tab">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>
<div class="tab">Tab 4</div>
</div>
The problem is, when I want to set up margin right on last element, it just wont move from the end of the div.. He gets the margin, you see it in the inspector but it just doesn't move.
The display:flex; on parent prevent margin to childs. To reach what you want, you can use transparent border:
.tab:last-child { border-right: 30px solid transparent; }
I know this is an old question but recently I had similar problems and my solution is to use ::before
or ::after
on the parent container depending if you want the first or last element (in this case) to have margin-right or padding-right.
.parent::after {
content: '';
border-left: 20px solid transparent;
}
Codepen
.parent {
display: flex;
overflow-x: auto;
padding: 15px 0 20px;
/*extra code for example purpose*/
background: aquamarine;
width: 450px;
}
.tab {
font-size: 15px;
text-transform: uppercase;
padding: 10px 40px;
color: #a4b5bf;
white-space: nowrap;
/*extra code for example purpose*/
background-color: teal;
}
/**
Having the before and after pseudo element in parent to mimic adding margin/padding to the first and last child element
NOTE: There's a possibility that sometimes border-left doesn't work and border works, which in this case, the border width should be half to accomodate the left and right border
**/
.parent::before,
.parent::after {
content: '';
border-left: 20px solid transparent;
}
<div class="parent">
<div class="tab">Tab 1</div>
<div class="tab">Tab 2</div>
<div class="tab">Tab 3</div>
<div class="tab">Tab 4</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With