Can I hide the element if it doesn't fit the available width using css only?

后端 未结 4 1945
盖世英雄少女心
盖世英雄少女心 2020-12-17 10:14

I have a header and an image that should be horizontally laid out on the absolutely positioned div. I\'m showing the text in the subdiv with the fixed width. I\'m trying to

相关标签:
4条回答
  • 2020-12-17 10:43

    What you will need to do is basically call a css file when the screen size is too small or too large in order to hide/show things that won't fit into the screen.

    <link rel='stylesheet' media='screen and (min-width: 701px) and (max-width: 900px)' href='css/medium.css' />
    
    0 讨论(0)
  • 2020-12-17 10:47

    If you'd like to hide overflowing elements and expand remaining elements to fit snugly, you can expand Shalom Aleichem's answer to do the trick:

    ul {
      border: 1px solid red;
      width: 350px;
      height: 100px;
      overflow: hidden;
      padding: 0;
      display: flex;
      flex-wrap: wrap;
    }
    
    ul > li  {
      border: 1px solid blue;
      display: block;
      flex: 1 0 100px;
      height: 100px;
      box-sizing: border-box;
    }
    <ul>
      <li>Item 1</li>
      <li>Item 2</li>
      <li>Item 3</li>
      <li>Item 4</li>
      <li>Item 5</li>
      <li>Item 6</li>
      <li>Item 7</li>
    </ul>

    More details available at this answer, and another approach using CSS grid is explained at this answer.

    0 讨论(0)
  • 2020-12-17 10:54

    I can think of two methods you might use to solve this. The first would be to set a max-width for any images of the container, this doesnt hide the image however:

    .container img{max-width:100%;}
    

    the second option would be to use responsive design based on screen size. Similar to what Thanos mentioned, but within the same stylesheet. However your question doesn't mention a change in the window size, simply a change in image size, so this is probably not what you want...

    @media screen and (max-width:500px){    
        .container img{display:none;}
    }
    

    A third option would be to use javascript, as you mentioned... I think this would be the easiest method.

    take a look at - http://css-tricks.com/forums/topic/conditionally-resize-image-based-on-width/

    0 讨论(0)
  • 2020-12-17 10:57

    I've found how this can be done. If I use display:block on the .container and float:left in the inner containers, the image will be wrapped if it doesn't fit the width. And if I use overflow: hidden, the image will be moved under the text and hidden.

    Here is the fiddle that proves this trick works: http://jsfiddle.net/8r72g/8/

    0 讨论(0)
提交回复
热议问题