简体   繁体   中英

Text centered next to image, and if no space, aligned to top

Let's check this fiddle :

img {
    float: left;
}

#inner {
    height: 128px; 
    background-color: yellowgreen; 
    display: table-cell;
    vertical-align: middle;
}

#content {
    background-color: red;
}

<img src="http://cdn.memegenerator.net/instances/250x250/37934290.jpg" width="128" height="128" />
<div id="inner">
    <div id="content">text text tertkl elknr tlken lsl kdmfsldkfmsldkfmslkd mfkndfln dflkfndg lkn</div>
</div>

this works so far as I expect - text is centered, and as you shrink the width, text goes underline: but then its "too far" from the image. The best would be if the vertical-align: middle; became vertical-align: top; when it needs to jump. How to do it without possibly jQuery?

A simple way to achieve this is to use a CSS Media Query .

Your markup would stay the same and your CSS would only need to have the following added:

@media screen and (max-width: 290px) {
    #inner {
        vertical-align: top;   
    }
}

in action: http://jsfiddle.net/uWMkH/1/

What that says is, "When the viewport's width is no more than 290px, do this stuff to #inner .

Take a look at these links for more information:

The caveat with using media queries to do this is that they aren't supported in IE8 and below. I hope you don't have to deal with those headaches!

Look here for a complete list of browsers with support:

You can do this without media queries, but it requires a browser that supports the entire CSS Flexible box module (most browsers are missing support for wrapping). At this point in time, support is limited to Opera, Chrome, and IE10.

http://codepen.io/cimmanon/pen/rFdkt

figure {
  display: -ms-flexbox;
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-pack: center;
  -webkit-justify-content: center;
  justify-content: center;
  -ms-flex-align: center;
  -webkit-align-items: center;
  align-items: center;
  background-color: yellowgreen;
}
@supports (flex-wrap: wrap) {
  figure {
    display: flex;
  }
}

figcaption {
  -webkit-flex: 1 15em;
  -ms-flex: 1 15em;
  flex: 1 15em;
  background-color: red;
}

What Flexbox offers over media queries is the ability to reflow the content based on the available space, not just the browser width.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM