Your users will not always open your application in a full-size desktop window. They may resize the browser, split the screen, rotate a tablet, or access the same page from a phone. Each change can affect navigation, forms, tables, images, and other responsive elements.
With Selenium WebDriver, you can set exact browser dimensions, maximise the window, or resize it during a test. This lets you check how the layout behaves at key CSS breakpoints and whether important elements stay visible, usable, and correctly positioned.
By the end of this article, you will know how to manage browser window sizes in Selenium, test multiple viewport widths, and configure headless runs for reliable responsive checks.
Why is Window Size Important in Responsive Testing?
A responsive layout changes according to the space available inside the browser. When the window becomes narrower, navigation may collapse, columns may stack, tables may require horizontal scrolling, and controls may move to different positions. Your Selenium tests need to account for these changes because the same element can behave differently at different widths.
Managing the window size helps you validate several parts of the responsive experience:
- Layout changes: Check whether grids, cards, sidebars, and content sections rearrange as expected.
- Element visibility: Confirm that important buttons, fields, messages, and navigation options are not hidden or pushed outside the visible area.
- Interaction changes: Verify that desktop menus switch to mobile controls and that these controls remain clickable.
- Content overflow: Detect text, images, tables, or fixed-width components that extend beyond their containers.
- Breakpoint behaviour: Test just below and above important CSS breakpoints instead of checking only a few common device sizes.
Note: You should also distinguish browser window size from screen resolution. Selenium can resize the browser window, but the page responds mainly to the viewport available for rendering content.
How to Set and Manage Browser Window Size in Selenium WebDriver?
Controlling the browser window size is crucial for responsive testing. Selenium WebDriver offers several ways to set, maximize, and dynamically resize the browser window during tests.
These features help testers simulate different device sizes and ensure web applications perform well across various screen resolutions. This section breaks down these methods with practical examples.
1. Set a Specific Window Size using WebDriver
Selenium WebDriver allows testers to define specific browser window dimensions to simulate different device screens. The set_window_size() method can be used to manually set the width and height of the browser window.
Explanation of the set_window_size() Method in Selenium WebDriver:
The set_window_size() method in Selenium enables testers to resize the browser window to a specified width and height in pixels. This is especially useful when testing responsiveness for predefined screen dimensions like those of smartphones, tablets, or desktops.
Example Code for Setting a Specific Window Size:
from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a URL
driver.get("https://example.com")
# Set browser window size to 1024x768
driver.set_window_size(1024, 768)
# Perform other actions
driver.quit()2. Maximizing the Window Size
Maximizing the browser window ensures that the website is displayed using the maximum available screen space. This is particularly helpful when testing desktop browser compatibility.
Explanation of the maximize_window() Method:
The maximize_window() method maximizes the browser window to the full size of the user’s display. This method ensures that the application utilizes the maximum available viewport area.
Example Code for Maximizing the Window:
from selenium import webdriver
# Initialize the WebDriver
driver = webdriver.Chrome()
# Open a URL
driver.get("https://example.com")
# Maximize the browser window
driver.maximize_window()
# Perform other actions
driver.quit()How to Dynamically Resize Browser Window using Selenium?
A responsive test may need to check more than one browser size. Instead of starting a separate Selenium session for every width, you can resize the current window and verify how the page responds after each change.
This approach is useful when you want to test:
- The point at which desktop navigation changes to a mobile menu
- Whether columns stack correctly on narrower screens
- How tables, modals, and sidebars behave after resizing
- Whether elements remain usable when the layout crosses a CSS breakpoint
1. Resize the Window Across Multiple Dimensions
The following example tests the same page at mobile, tablet, and desktop window sizes:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
window_sizes = [
{"name": "Mobile", "width": 390, "height": 844},
{"name": "Tablet", "width": 768, "height": 1024},
{"name": "Desktop", "width": 1440, "height": 900},
]
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)
try:
driver.get("https://your-application.example")
for size in window_sizes:
driver.set_window_size(size["width"], size["height"])
wait.until(
lambda current_driver:
current_driver.get_window_size()["width"] == size["width"]
)
print(
f'Testing {size["name"]}: '
f'{size["width"]}x{size["height"]}'
)
# Add assertions for the layout expected at this size.
assert driver.find_element(By.TAG_NAME, "body").is_displayed()
finally:
driver.quit()Output –
Avoid using a fixed delay such as time.sleep() after every resize. A layout may update immediately on one machine but take longer in another test environment. Wait for the browser dimensions or a specific responsive element to reach the expected state instead.
Read More: What is UI Responsiveness Testing?
2. Test Around CSS Breakpoints
Testing only common device dimensions may leave gaps in your coverage. Responsive defects often appear at the exact point where one layout changes into another.
Suppose the application switches to mobile navigation at 768px. Test widths on both sides of that breakpoint:
breakpoint_widths = [767, 768, 769]
for width in breakpoint_widths:
driver.set_window_size(width, 900)
viewport_width = driver.execute_script(
"return window.innerWidth;"
)
print(
f"Window width: {width}, "
f"viewport width: {viewport_width}"
)
# Verify the correct navigation for the resulting viewport.Output –
Testing 767px, 768px, and 769px can reveal boundary defects that a general mobile or desktop test would miss. Use the breakpoints defined by your application rather than relying only on a standard list of device sizes.
Also Read: A Complete Guide to CSS Media Query [2026]
3. Verify the Viewport After Resizing
The dimensions passed to set_window_size() apply to the outer browser window. The page itself responds to the viewport, which excludes browser controls and window borders.
You can read the resulting viewport dimensions with JavaScript:
viewport = driver.execute_script(
"""
return {
width: window.innerWidth,
height: window.innerHeight
};
"""
)
print(
f'Viewport: {viewport["width"]}x{viewport["height"]}'
)Output –
This check matters when your assertion depends on an exact CSS breakpoint. A browser window set to 768px wide may provide a slightly different content width depending on the browser and operating system.
For stricter viewport testing, calculate the difference between the outer window and the viewport, then adjust the window:
def set_viewport_size(driver, width, height):
window = driver.get_window_size()
viewport = driver.execute_script(
"""
return {
width: window.innerWidth,
height: window.innerHeight
};
"""
)
width_difference = window["width"] - viewport["width"]
height_difference = window["height"] - viewport["height"]
driver.set_window_size(
width + width_difference,
height + height_difference
)Output –
You can then request a specific viewport size:
set_viewport_size(driver, 768, 900)
Output –
Read window.innerWidth again after the adjustment if the test requires exact dimensions. Some environments may enforce minimum window sizes or apply additional browser decorations.
4. Dynamically Resize a Headless Browser
Headless tests also need an explicit window size. Without one, the browser may use a default size that activates a different responsive layout from the one you expected.
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless=new")
driver = webdriver.Chrome(options=options)
try:
driver.set_window_size(1280, 800)
driver.get("https://your-application.example")
viewport_width = driver.execute_script(
"return window.innerWidth;"
)
print(f"Headless viewport width: {viewport_width}")
finally:
driver.quit()Output –
Use the same dimensions in local and CI runs when you expect the same layout. This prevents a test from passing on your machine but failing in a headless pipeline because the two sessions opened at different sizes.
5. Use WebDriver Instead of JavaScript to Resize the Window
You may find examples that call window.resizeTo() through Selenium’s JavaScript executor. For standard browser-window resizing, use set_window_size() instead.
The Selenium WebDriver method expresses the action directly and lets Selenium send the appropriate window-management command to the browser. JavaScript-based resizing can also be restricted by browser security rules or behave differently depending on how the window was opened.
Use JavaScript to read viewport values such as window.innerWidth. Use Selenium’s window-management methods when you need to change the browser dimensions.
Common Use Cases for Managing Window Size in Selenium
Managing browser window sizes in Selenium is key to testing how web applications perform on different devices.
Here are some of the most common scenarios where adjusting the window size comes in handy:
- Responsive Design Testing: Web applications need to work smoothly across a range of devices, from desktops to tablets and smartphones. Adjusting the browser window size lets testers verify that layouts remain consistent and catch issues like overlapping content or hidden elements.
- Simulating Real-World User Behavior: Since users access websites from various devices with different screen sizes, resizing the browser window during tests helps simulate those real-world conditions. This ensures the application delivers a seamless experience no matter the device.
- Verifying Adaptive Layouts: Many web applications use layouts that change depending on screen size. Adjusting the window size allows testers to confirm that content shifts and rearranges correctly without disrupting the user experience.
- Testing on Headless Browsers: Headless browsers run tests without a graphical interface, making them ideal for faster, automated testing. Setting the window size ensures tests are realistic, even when no UI is displayed, and is especially useful in CI/CD pipelines.
- Debugging Layout Issues: To troubleshoot layout problems, testers often need to replicate specific screen sizes. Changing the browser window size helps recreate these issues so they can be diagnosed and fixed more effectively.
- Cross-Browser Compatibility: Web applications need to perform well across different browsers. Managing window sizes ensures the app behaves consistently at various screen resolutions, making it easier to spot any discrepancies between browsers.
- Testing Popups and Overlays: Popups, modals, and overlays can behave differently on smaller screens. By resizing the window, testers ensure that these elements remain functional and accessible no matter the screen size.
- Accessibility Testing: Some users may have trouble accessing content on certain screen sizes. Testing with different window sizes helps ensure the application is accessible and meets the needs of all users, regardless of their device.
Challenges in Testing Responsive Design
Responsive testing becomes difficult when you move beyond checking whether a page “looks fine” at a few common widths. A reliable test must account for breakpoint logic, viewport differences, browser behaviour, dynamic content, and the limits of resizing a desktop browser.
The following challenges are the ones most likely to affect Selenium tests.
1. Choosing Meaningful Test Sizes
You cannot test every possible width and height. A list based only on popular device resolutions can also leave gaps because responsive layouts change at CSS breakpoints, not at device names.
Build your test set around:
- The breakpoints defined in the application
- One width below and above each important breakpoint
- Common desktop, tablet, and mobile viewport ranges
- Dimensions linked to defects reported by users
- Narrow or unusually short windows that may expose overflow
For example, if a navigation menu changes at 768px, testing only 375px and 1440px will confirm the two layouts but not the transition between them. Widths such as 767px, 768px, and 769px provide better boundary coverage.
2. Distinguishing Window Size from Viewport Size
Selenium’s set_window_size() changes the outer browser window. Your CSS media queries respond to the viewport inside that window.
Browser tabs, borders, toolbars, and operating system decorations can reduce the available viewport. As a result, setting a window width of 768px does not always produce a viewport width of 768px.
This difference becomes important when you test exact breakpoint behaviour. Read window.innerWidth and window.innerHeight after resizing instead of assuming the requested window dimensions match the rendered page area.
3. Waiting for the Layout to Finish Updating
Responsive changes are not always complete as soon as Selenium resizes the window. The application may need to:
- Recalculate element positions
- Run resize-event handlers
- Load a different image source
- Re-render framework components
- Open or close navigation elements
- Apply transitions or animations
An assertion executed immediately after resizing may inspect the old layout or catch the page halfway through a transition.
Avoid fixed delays where possible. Wait for a meaningful layout condition instead, such as the mobile menu becoming visible, the desktop navigation disappearing, or a column moving below another element.
4. Writing Assertions That Match Each Layout
The same feature may use different elements at different widths. A desktop navigation bar may be replaced by a menu button. A table may become a set of cards. A sidebar may move below the main content.
A single locator or visibility assertion may therefore fail even when the responsive design is correct.
Structure your test around expected behaviour at each layout. For example:
- At desktop width, verify that the full navigation is visible.
- At mobile width, verify that the full navigation is hidden.
- Confirm that the menu button appears and opens the same navigation options.
- Check that the user can still complete the original task.
The goal is not to prove that every element stays in the same place. It is to verify that the feature remains available and usable after the layout changes.
5. Detecting Visual Defects with Functional Assertions
Selenium can confirm that an element exists, is displayed, and accepts input. Those checks may not reveal that the element overlaps another control, extends outside its container, or is partly hidden.
Responsive defects often involve geometry rather than basic availability. You may need to inspect element dimensions and positions with get_rect() or JavaScript. For broader visual coverage, screenshot comparison can help detect spacing, alignment, clipping, and layout shifts that ordinary functional assertions miss.
Use visual checks selectively. They are most valuable for stable components and key layouts because minor rendering differences can create noisy failures.
6. Handling Browser-Specific Rendering
Two browsers can receive the same CSS and still produce small differences in text wrapping, scrollbar behaviour, form controls, font rendering, and available viewport space. These differences may cause an element to cross a breakpoint or overflow only in one browser.
A responsive test that passes in Chrome should not be treated as proof that the layout works in Firefox, Edge, or Safari. Run important breakpoint and interaction tests across the browsers in your support matrix.
When a failure occurs in only one browser, check the resulting viewport size and computed layout before assuming the browser ignored the requested window dimensions.
7. Managing Headless and CI Differences
Headless browsers may start with a default window size that differs from your local browser. CI environments can also use different fonts, operating systems, display settings, or browser versions.
These differences can affect:
- Text wrapping
- Element height
- Scroll position
- Screenshot output
- Responsive breakpoints
- The position of fixed or sticky elements
Set the browser size explicitly in every headless test. Keep browser versions and test configuration consistent where possible. When debugging a CI-only failure, capture the actual window size, viewport size, browser version, and screenshot rather than relying only on the local result.
8. Understanding the Limits of Browser Resizing
Resizing a desktop browser is useful for checking CSS breakpoints and layout changes, but it does not reproduce a complete mobile environment.
It does not automatically simulate:
- Touch input
- Mobile browser controls
- Device pixel ratio
- Physical screen density
- Orientation events
- On-screen keyboards
- Mobile operating system behaviour
- CPU, memory, or network constraints
Use Selenium window resizing for responsive layout checks and browser-based interactions. Use mobile emulation or real-device testing when the behaviour depends on device characteristics rather than viewport width alone.
Best Practices for Managing Window Size in Selenium
Window-size tests become difficult to maintain when dimensions are scattered across test files or when one test tries to validate every responsive layout. The following practices help you keep the test suite predictable and easier to debug.
1. Set the Window Size Before Loading the Page
For tests that validate a fixed layout, set the required dimensions before calling driver.get().
Some applications make decisions during the initial page load. They may select image sources, initialise carousels, calculate component dimensions, or register layout-specific behaviour based on the available space. Resizing only after the page has loaded may not reproduce the same state as opening it at that size.
driver = webdriver.Chrome()
driver.set_window_size(390, 844)
driver.get("https://your-application.example")Output –
Resize the browser after navigation only when the test specifically checks how the application reacts to a live size change.
2. Store Window Profiles in One Place
Avoid repeating values such as 390×844 or 1440×900 throughout the test suite. Define named window profiles in a shared configuration and pass them into the relevant tests.
WINDOW_PROFILES = {
"compact": {"width": 390, "height": 844},
"medium": {"width": 768, "height": 1024},
"wide": {"width": 1440, "height": 900},
}Output –
Named profiles make failures easier to understand and allow you to update a dimension without editing several test files. The names should describe the layout being tested rather than a specific device model unless the test genuinely depends on that device.
3. Parameterise Tests Instead of Copying Them
If the same user flow must work at several window sizes, use the dimensions as test data. Do not create separate test functions with nearly identical steps.
import pytest
@pytest.mark.parametrize(
"width,height",
[
(390, 844),
(768, 1024),
(1440, 900),
],
)
def test_checkout_remains_usable(driver, width, height):
driver.set_window_size(width, height)
driver.get("https://your-application.example/checkout")
# Complete the same checkout checks at each size.Output –
Parameterisation keeps the shared behaviour in one test while still reporting each size as a separate case. Use separate tests only when the workflow changes significantly between layouts.
4. Separate Fixed-Size Tests from Resize Tests
A fixed-size test and a dynamic resize test answer different questions.
A fixed-size test checks how the page behaves when it opens at a particular dimension. A resize test checks whether the application responds correctly when the dimensions change during the session.
Keep these scenarios separate. Otherwise, a failure may come from the initial layout, the resize handler, retained component state, or the final layout, which makes the cause harder to identify.
For most functional flows, open the page at the target size and keep that size unchanged. Reserve dynamic resizing for components that are expected to react while the page is already open.
5. Capture Window Details When a Test Fails
A failure report should show the dimensions the browser actually used. Record the requested window size, the reported window size, the current URL, and a screenshot.
window_size = driver.get_window_size()
print(
f'Actual window size: '
f'{window_size["width"]}x{window_size["height"]}'
)
driver.save_screenshot("responsive-test-failure.png")Output –
Include the profile name in the test ID or screenshot filename. A report labelled compact-checkout is more useful than one that only says the checkout test failed.
These details make it easier to reproduce the failure locally and confirm that the test ran with the intended configuration.
Conclusion
Managing browser window size in Selenium helps you test how layouts and key interactions behave across different widths. Use fixed dimensions for stable responsive checks and dynamic resizing only when you need to verify live layout changes.
Focus on the breakpoints that matter, confirm the actual viewport when precision is required, and capture the final window size when a test fails. Window resizing is useful for responsive testing, but real-device checks are still needed for touch, mobile browsers, and device-specific behaviour.









