Home > Mobile >  Pure CSS Style element if it wrapped or not (without Javascript)
Pure CSS Style element if it wrapped or not (without Javascript)

Time:10-13

In the following clip, if the #TWO wraps, I wish to not show the black left border of #TWO. The black border is to separate the items visually when they are aside only. When wrapped having the border between them vertically is okay too.

Currently I do this with JavaScript (e.g. if (TWO.offsetLeft > 50) ...), but hope it might be doable with purely CSS.

#PARENT {
  display: flex;
  flex-wrap: wrap;
}

.child {
  padding: 16px;  
}

#ONE {
  background: #fee;
}

#TWO {
  background: #efe;
  border-left: 2px solid black;
}
<div id="PARENT">
  <div id="ONE" >One sentenance that is long or maybe short</div>
  <div id="TWO" >Two is also unknown length</div>
</div>

Update: Made it more apparent that the width is determined by the content, not some fixed static value.

CodePudding user response:

Why not use media queries?

/* adding to neutralize default browser styles */
body { 
  margin: 0;
}
/* adding to make math easier */
* {
  box-sizing: border-box;
}

#PARENT {
  display: flex;
  flex-wrap: wrap;
}

.child {
  min-width: 200px;
  padding: 16px;  
}

#ONE {
  background: #fee;
}

#TWO {
  background: #efe;
}

@media screen and (min-width: 400px) { 
    #TWO {
      border-left: 2px solid black;
    }
}
<div id="PARENT">
  <div id="ONE" >one</div>
  <div id="TWO" >two</div>
</div>

CodePudding user response:

Using @TemaniAfif's comment:

Use the gap property and add background to the container

PS: If you post a solution I will delete this answer:

#PARENT {
  display: flex;
  flex-wrap: wrap;
  background: black;
  gap: 2px;
}

.child {
  padding: 16px;
  flex-grow: 1;
}

#ONE {
  background: #fee;
}

#TWO {
  background: #efe;
}
<div id="PARENT">
  <div id="ONE" >One sentenance that is long or maybe short</div>
  <div id="TWO" >Two is also unknown length</div>
</div>

  •  Tags:  
  • css
  • Related