Insert figures for a subsection and start another subsection after image

\subsection{Subsec1}
First content
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.25\textwidth]{fig1.png}
\caption{W}
\label{fig: W}
\end{center}
\end{figure}

\subsection{subsec2}
Second content
\begin{figure}[h!]
\begin{center}
\includegraphics[width=0.25\textwidth]{fig2.png}
\caption{D}
\label{fig: D}
\end{center}
\end{figure}


There are contents above subsec1 and below subsec2. in the output pdf, the subsec1 is in second half of a sheet. So, there no enough space for the fig1. This makes the subsec2 to fill the space after subsec1 and pushes my fig1 after subsec2. This makes the fig1 and fig2 one after the other. But I need the subsec2 between these two figs.

What should I change ?

• Your wording is completely confusing. How about your write what you want, rather than what is happening. If the intent is to keep figure where they're mentioned, then add the float package and use the [H]ere float specification. – Werner Apr 28 '17 at 1:54

Add \usepackage{float} to your preamble, and then change your where variable [h!] to [H], this will hold the figure exactly where you specify it.

To tell the true, if you use float package with H option it's like to give a ball to a child and then tell him "don't play soccer!".

Moreover, in your mwe you have used a center environment within a figure one, which is not good, because it results in an extra vertical space added.

If you don't want your figure float, simply don't use a figure environment. It's sufficient the center one with capt-of package for the caption:

\documentclass{book}
\usepackage{graphicx}
\usepackage{capt-of}

\begin{document}
\subsection{Subsec1}
First content
\begin{center}
\includegraphics[width=0.25\textwidth]{example-image-a}
\captionof{figure}{W}
\label{fig: W}
\end{center}

\subsection{subsec2}
Second content
\begin{center}
\includegraphics[width=0.25\textwidth]{example-image-b}
\captionof{figure}{D}
\label{fig: D}
\end{center}
\listoffigures
\end{document}


I've also added \listoffigures just to show that there are no problems in not using figure environment: