奚文正 奚文正 - 2 months ago 6
CSS Question

I gave ngative margin,and the parent div gave more width,but the picture can't in the right way

it works, I increase the parent box's width

But the last picture still not raise .

I want the picture in the same row
See the image that I want

Here are my HTML code.

<div class="main-show">
<ul>
<li><img src="./images/pic_1.jpg" alt=""></li>
<li><img src="./images/pic_2.jpg" alt=""></li>
<li><img src="./images/pic_3.jpg" alt=""></li>
<li><img src="./images/pic_4.jpg" alt=""></li>
<li><img src="./images/pic_5.jpg" alt=""></li>
</ul>
</div>


and CSS Code

.main-show{
width: 100%;
}
.main-show ul{
margin-right: -25px;
overflow:hidden;
}
.main-show li{
float: left;
width: 20%;
margin-right: 5px;
}
.main-show img{
width: 100%;
float: left;
}

Answer

You can use the CSS calc() function to calculate a proper width for the li elements, in your case reduce the 20% by the 5px margin:

width: calc(20% - 5px);

Sidenote: You don't need the float on the img as you are already floating the li elements.

Update: If you want to remove the last right margin, you should use the selector li:last-child and set the margin-right: 0;. Now you have to use width: calc(20% - 4px); because of the missing last 5px.

body {
  background: black;
}
.main-show {
  width: 100%;
  background: white;
}
.main-show ul {
  padding-left: 0;
  overflow: hidden;
  list-style-type: none;
}
.main-show li {
  float: left;
  width: calc(20% - 4px);
  margin-right: 5px;
}
.main-show li:last-child {
  margin-right: 0;
}
.main-show img {
  width: 100%;
}
<div class="main-show">
  <ul>
    <li>
      <img src="http://placehold.it/200" alt="">
    </li>
    <li>
      <img src="http://placehold.it/200" alt="">
    </li>
    <li>
      <img src="http://placehold.it/200" alt="">
    </li>
    <li>
      <img src="http://placehold.it/200" alt="">
    </li>
    <li>
      <img src="http://placehold.it/200" alt="">
    </li>
  </ul>
</div>