Minecraft wiki entry for Nether_portals, associated text: First the game calculates the "ideal" destination coordinate as above, dividing or multiplying the traveler's X and Z coordinates by 8. It then searches for existing portals (actual portal blocks) within nearby chunks.
If going to the Nether it searches a 3x3 chunk area (that is, the chunk of the "ideal" coordinates, and the adjacent chunks).
If going to the Overworld, it searches a much larger area, 17x17 chunks (that is, up to 8 chunks away from the original point).
In either dimension, the entire vertical range of the world is scanned.
For any column of portal blocks (such as the two 3-high columns of a "standard" portal), only the bottom one is considered.
If any portals are found in this range, the traveler is teleported to the closest of them, based on the Euclidean (not taxicab) distance in all three coordinates. Differences in the Y coordinate can bypass the portal that's closest in only X and Z!
If no portals are found within range, the game sets out to make a portal:
It searches within 16 blocks horizontally (but any distance vertically) of the player's destination coordinates.
For the first pass, a valid location is 3×4 buildable blocks with air 4 high above all 12 blocks. When enough space is available, the orientation of the portal is random. The closest valid position in the 3D distance is always picked.
If no such space is found, it tries again looking for a narrower fit: A 1x4 area of buildable blocks, still with air 4 high above them.
If both of the above fail, the game forces a portal:
The ideal X and Z coordinates are used, but Y is clipped to be between 70, and 10 below the world height (i.e. 118 for the Nether or 246 for the Overworld).
A 2×3 platform of obsidian with air 3 high above is created at the target location, overwriting whatever might be there. This provides air space underground, or a small platform if high in the air. In Bedrock Edition, the platform includes 4 more blocks of netherrack on each side, a total of 12 blocks of platform.
When creating a portal, the game always makes a 4x5 frame of obsidian, including corner blocks.