简体   繁体   中英

Position images side by side

I am trying to align two images horizontally on my page and then another two underneath them horizontally so that I end up with a grid of four images all contained within a div.

I have the images contained within the div I just cannot align them to how I want them to be.

Edit:

The parent div need to have a width of 100%. The img need have 50% as width. Give a specific height to your img so that they all have the same. Add box-sizing: border-box; so that your padding will be calculated in the width. Finally add float: left; to place the image.

I don't recommand diplay: flex since not all browser support it.

.parent {
  width:100%;
}
.parent img {
  width: 50%;
  box-sizing: border-box;
  float: left;
  padding: 5px;
}

https://jsfiddle.net/L8vx30v0/2/

Well, if you have only 4 images you could go for the simpliest solution with two lists and display: flex

https://jsfiddle.net/dgsgy1Ly/1/

There are multiple ways to achieve this.
Positioning is one of the main parts of CSS.

  1. set container width eg:
    .container { width: 600px; }
    set child to a fraction of containers size
    .child { width: 250px; }
    note.: if .child is a <div> remember to set .child's display: inline-block;
  2. same as above but with dynamic units . %, vh, vw, em, rem
  3. use CSS3 Flexbox :
.container {
  width: 600px;
  display: flex; 
  flex-wrap: wrap; 
  justify-content: center; 
  align-items: center; 
}
.child {
  width: 250px;               /* fraction of container's size */
  margin: 2px;
}
  1. use a Layout Framework's grid, eg: Bootstrap .
<div class="container">
  <div class="row text-center">
    <img>
    <img>
  </div>
  <div class="row text-center">
    <img>
    <img>
  </div>
</div>

here's a fiddle with the 4 examples. https://jsfiddle.net/warkentien2/otgns8hx/1/

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