Responsive layout without media query

℡╲_俬逩灬. 提交于 2020-01-25 02:31:53

问题


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.


回答1:


It's possible if you wrap the boxes inside a new container and add the box margin as a negative value on the new container. See https://jsfiddle.net/qnop1wb8/9/ :)

Or see this example:

Note that I've decreased the flex-basis values on the boxes for inline example purposes. The jsfiddle link has your values.

.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; /* Note: decreased width for this inline example */
  height: 100px;
  background: blue;
}

.box2 {
  flex: 1 1 100px; /* Note: decreased width for this inline example */
  height: 100px;
  background: yellow;
}
<div class="wrapper">
<div class="wrapper__body">

<div class="box1">

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

</div>
</div>
</div>



回答2:


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

beautiful video Jen Simmoons

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




回答3:


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


来源:https://stackoverflow.com/questions/49637661/responsive-layout-without-media-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!