The way you would have to do this is to continually monitor the voltage of the battery and the current into or out of the battery. Using the numbers you can both monitor the amount of energy over time being pushed into the battery during charging and then turn around and monitor amount of energy being drained from the battery over time when it is in the discharge mode.
Measuring the current into or out of the battery is done by inserting a known small resistance in series with the battery and then measuring the small voltage drop across this resistor which will be proportional to the current. Sometimes the small resistance is derived from the wiring or or connection materials themselves without actually using a discrete resistor component.
Another thing to establish are the data points that represent when the battery is fully charged and when it is considered discharged (although this may not ever be a fully discharged battery because that state can totally wreck a battery).
Knowing this data and tracking this over a number of charge cycles you can develop a profile of battery usage time from the full to the empty state. Once the profile is established you judge remaining battery capacity not on the basis of its terminal voltage but rather on the total amount of energy over time that you have removed from the battery while it is in use.
Note that for certain pieces of equipment that has a high manufacturing volume and a consistent battery technology it is possible to have the software coded to show a really good estimate of the remaining capacity when the battery is new and has been fully charged the first time. This is possible because the usable capacity of the average battery can be found. This piece of equipment can still keep a running process of monitoring energy over time in and out of the battery to be able to track the changes of the battery behavior over many charge/discharge cycles.
Finally note that it is common that battery packs or subsystems with integral battery units contain a small standalone chip called a battery monitor device (or as often referred to as a "battery gas gauge chip"). These are powered right off the battery and contain a current and voltage monitor that is able to calculate charge in and out of the battery. These simply operate a counter of available charge in the battery that increments when the battery is charged and decrements when the battery is under load. A one or two wire serial interface into these monitor chips lets a host MCU or computer monitor the battery capacity by reading the counter out. The serial interface may also allow for reading battery temperature in cases where the pack contains a thermistor that is connected to the monitor chip.