Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot give margin right to last element in div with scroll?

Tags:

html

css

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.

like image 219
Nemanja G Avatar asked Jan 30 '23 20:01

Nemanja G


2 Answers

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;
    }

like image 170
kastriotcunaku Avatar answered Feb 03 '23 04:02

kastriotcunaku


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>
like image 25
Omar Tan Avatar answered Feb 03 '23 04:02

Omar Tan