1

I'm looking for a creative way of doing responsive layout without media query.

Let's say I have a row of two boxes. First one has min width of 400px. Second one has min width of 200px. The gap between them is fixed width 60px.

If the container is larger than 660px, then two boxes should expand proportionally. If the container is less than 660px, then the second box should go to next line, and both boxes' widths should be 100%.

I almost got it with css flexbox. See here. Except that when the container is less than 660px, the first box's width doesn't expand to 100% (because of fixed margin-right: 60px).

I know it's easy to achieve with media query or some css frameworks like bootstrap, but I want to see if it's possible without media query.

I've been looking into flexbox and css grid for such possibility but no success. Any help is appreciated.

EDIT:

The reason behind this is that I want to build a responsive layout based on the container's width, not viewport's width. Element Query solves this but it's not implemented in major browsers yet.

Shawn
  • 2,675
  • 3
  • 25
  • 48

3 Answers3

2

It is possible if you wrap the boxes in a new container and give this container a style with the margin of the boxes inside as a negative value. See https://jsfiddle.net/qnop1wb8/9/

.wrapper {
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
}

.wrapper__body {
  flex: 1;
  margin: 0 -30px;
  display: inherit;
  flex-wrap: inherit;
}

[class*="box"] {
  margin: 0 30px;
}

.box1 {
  flex: 1 1 200px;
  height: 100px;
  background: blue;
}

.box2 {
  flex: 1 1 100px;
  height: 100px;
  background: yellow;
}
<div class="wrapper">
<div class="wrapper__body">

<div class="box1">

</div>
<div class="box2">

</div>
</div>
</div>
CoenFuze
  • 484
  • 2
  • 7
  • Actually you don't need two wrappers to make it work. One wrapper is enough. See [here](https://jsfiddle.net/qnop1wb8/14/). But your solution works!!! – Shawn Apr 04 '18 at 23:46
  • That's correct, but you may get overflows. So I would suggest to use the body as well so you could set overflow: hidden; on the "actual" parent (.wrapper in this case). This has advantages if your placing it in nested layouts with paddings or margins. – CoenFuze Apr 04 '18 at 23:54
  • You are right, but the actual parent wouldn't need `display: flex` and `flex-wrap`, right? – Shawn Apr 05 '18 at 00:01
1

display: grid and grid-template-colums: repeat(auto-fill, minmax(200px, 1f))

beautiful video Jen Simmoons

https://www.youtube.com/watch?v=tFKrK4eAiUQ

Fatih Hayrioğlu
  • 3,458
  • 1
  • 26
  • 46
0

If you don't want to use css media queries, javascript is the only option with the resize event:

window.addEventListener("resize", () => {
    if(window.innerWidth > 1000){
        // do something if window is bigger than 1000px
    } else {
        // do something else
    }
});
Alex C
  • 516
  • 7
  • 15