When a condition fails, the default style in the CSS media query does not apply

Whenever the user resizes the browser, my media query for max-width kicks in to make the design responsive. But I'm facing an issue where when the user returns back to the original browser size, the design is still a little messed up and doesn't return to its initial position. It seems like no media query rules are being removed when the condition isn't met and default CSS should be applied instead.

Before resizing:

After resizing:

After reverting resize:

.nav-main-link {
    display: inline-block;
    border-right: 1px solid black;
    min-height: 50px;
}

#nav-main-search {
    float: right;
    margin-top: 10px;
    margin-right: 10px;
}

#nav-main-search .search-input {
    border-radius: 5px 0px 0px 5px;
    width: 225px;
    font-size: 1.0em;
    box-sizing: border-box;
    padding: 2px 0px 0px 10px;
    height: 2em;
}

@media (max-width: 600px) {

    .nav-main-link {
        display: block;
        border-bottom: 1px solid white;
        border-right: 0;
    }

    #nav-main-search {
        float: none;
        position: relative;
        padding-bottom: 10px;
        padding-left: 10px;
        padding-right: 50px; 
    }

    #nav-main-search .search-input {
        display: block;
        width: 100%;
    }   

        #nav-main-search button[type="submit"]{
        position: absolute;
        top: 0px;
        right: 0px;
    }

}

UPDATE: included jsfiddle demo DEMO: https://jsfiddle.net/qtenuuhv/

Answer №1

After testing this issue in various browsers, it seems to be isolated to affecting Chrome only. The conflict arises from using display: inline-block; on .nav-main-link and float: right; on #nav-main-search.

To resolve the problem, simply change the styling by floating .nav-main-link to the left instead of using inline-block:

  • Add float: left; to .nav-main-link
  • Remove display: inline-block; from .nav-main-link

* {
  border: 0;
  padding: 0;
  margin: 0;
}
a {
  text-decoration: none;
}
ul {
  list-style-type: none;
}
body {
  font-family: Arial, Sans-Serif;
  font-size: 0.9em;
}
#main {
  min-width: 300px;
  max-width: 900px;
  margin: 0 auto;
  padding: 10px 20px 0 20px;
}
#nav-main {
  background: #936ac9;
  background: -moz-linear-gradient(top, #936ac9 0%, #8745bc 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #936ac9), color-stop(100%, #8745bc));
  background: -webkit-linear-gradient(top, #936ac9 0%, #8745bc 100%);
  background: -o-linear-gradient(top, #936ac9 0%, #8745bc 100%);
  background: -ms-linear-gradient(top, #936ac9 0%, #8745bc 100%);
  background: linear-gradient(to bottom, #936ac9 0%, #8745bc 100%);
  filter: progid: DXImageTransform.Microsoft.gradient(startColorstr='#936ac9', endColorstr='#8745bc', GradientType=0);
  min-height: 50px;
  overflow: hidden;
  border-radius: 10px;
}
#nav-main a {
  color: white;
}
#nav-main-search {
  float: right;
  margin-top: 10px;
  margin-right: 10px;
}
#nav-main-search .search-input {
  border-radius: 5px 0px 0px 5px;
  width: 225px;
  font-size: 1.0em;
  box-sizing: border-box;
  padding: 2px 0px 0px 10px;
  height: 2em;
}
.nav-main-link {
  float: left; /*Add this*/
  /*display: inline-block; Remove this*/
  border-right: 1px solid black;
  min-height: 50px;
}
.nav-main-link a {
  display: block;
  font-size: 1.3em;
  padding: 12px 10px;
  border-right: 1px solid white;
iPointXYZ
.clientY<ID:B-19
&displayBlock();minHeight-Findex-Main-GotoMarketing_customize-pattern_choices)-Ocean-Interaction{
.limit[?];Index((SomePropertyNoPrefix==margin-bottom){
.continue.spawn="";
.float:left;}
Index((SomeProperty==text-weight){
.modify("");
Italic();}
.properties.getIndex.indent().configure()
center-align(points.marginTop).css(rightInherit){
.kill{ ThisIsTheFirstChoice!important(){Applying-this.default().caret('pointer').cursor(...)not(...)}
pointers{}initialized=False()})
defaultParams=this.type.defaults['TopicID-000.js']['nesting','capitalize']){
.addition.select('_');
appender.addElement("[0]",addItem());
setDefaultHandlers(new InitialActionRegisterHandler()){=}test_its
Boolean=!Error occurred SystemHandling('?cannot handleXML-LayersWas.Null.parent='<but still [to] testToLocalize]);
@includechoose(self.selWrapper())
args.childsxaddErrorToInterfaceX(changeHandlerForSelection)
setProcessingMode(new OverrideClassBuilder(calculateGeneralPatternIndentLongDocumentation()));

                              Index({focus-counter","addStyleDocument.EditorWithEditable()(editor:invoke()));Invoke()]);
                  Index()+styling-right)){
xyz_bottom.click();
                  focusCoordinates(EditorHighlightTill('endDrag.Stop()
                      connectCoordinate(ItemDrag,['mouseHoverEscape']);
                }
);
this.insertContent(position.xElement)/indentation(findAnimation.handler.getFirstFocusWindow().execute());
.runOnTime(parent.detectNullFunctionality(handler.dragOperation))
bookmark(authorizationAuthenticationStatus.actionable(documentServices).load(dataNotFound([{import}],"accessibleFile","preventOverwriting")
.hideSystemRelatedObjects(triggerPoint(containerObserver)).changeLanguage().restorePreselectedItemsRedemption())}/>
    IF(fetchedData!==""){
      return data_response
      }ELSE-PAGE-OFFSET(/base){selectiveFilter([ORDER-BY(ROOT-TARGET)],'CORE')(regular/pageId].get.relative(anchor.position)shouldBe*/)(`run (BlocklyPlugin(hex_id)))
resetDebugLevel();

SyntaxHelper.GotoThis('.suppress=function.propagate()')
centerViewport(propertyName.getDependencies(fromDependent[out])
.parse.this(By.super.query(sCallCount++));

lambda_expression("("");
evaluate.intersect(doDOMManipulations.find(pointOfIntersect.Equals())){

.ActNow("checkpointsByEffect.contains(interactions))");

.maximizeExpression(memoryImpactCheck.calculate(doc)

.method_orderCaseInsensitive(driver).representativeEachQuery(){

        enforceMemoryRestrictions(userAgent.classificationComparison(IBAN)));
              pageLoadState(getFilterButtonDirective(pathFinder.positiveNav.element.trigger()),
                                dropVisibleElement.button.displayNavigation(preparePagination.preferredDisplay.minEvents,
                                  defaultClass(interface.pointerEventHandler)),
requestConfirmation_for_all(selection.ensureUserProvided()));
}信DBC雅话通H序为间专务122.productions-init/plainTextKANJI(\'共响招\')";

                            @media (max-width: 600px) {
                                .nav-main-link {
                                    float: none; /*Add this*/
                                    display: block;
                                    border-bottom: 1px solid white;
                                    border-right: 0;
                                }
                                #nav-main-search {
                                    float: none;
                                    position: relative;
                                    padding-bottom: 10px;
                                    padding-left: 10px;
                                    padding-right: 50px;
                                }
                                #nav-main-search .search-input {
                                    display: block;
                                    width: 100%;
                                }
                                #nav-main-search button[type="submit"] {
                                    position: absolute;
                                    top: 0px;
                                    right: 0px;
                                }
                            }
<div id="main">
  <nav>
    <ul id="nav-main">
      <li class="nav-main-link"><a href="#">News</a>
      </li>
      <li class="nav-main-link"><a href="#">Contact</a>
      </li>
      <li class="nav-main-link"><a href="#">Careers</a>
      </li>
      <li id="nav-main-search">
        <form method="post" enctype="application/x-www-form-urlencoded" action="#">
          <input placeholder="Search..." class="search-input" type="text" />
          <button type="submit" value="search"><i class="fa fa-search"></i>
          </button>
        </form>
      </li>
    </ul>
  </nav>
</div>

JS Fiddle: https://jsfiddle.net/q9r6xgyL/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjust the size of a div while maintaining its aspect ratio based on the width and height of its parent element using CSS

After exploring various methods to create div aspect ratios using CSS, I had success with a demo. However, I encountered an issue with setting the height of my container when the width-to-height ratio is larger (#1 scenario). https://i.sstatic.net/VNdJ5.p ...

Looking for assistance in merging CSS and HTML codes?

I am working on combining two different codes and could use some assistance. Here is the HTML code: <div class="loader"> <span></span> <span></span> <span></span> </div> Followed by the CSS cod ...

Steps to create a hover effect that alters the appearance of another chosen "element"

For instance, I have two classes named A and B. I want to be able to change the appearance of B when I hover over it, such as its color or size. I am unsure if this can be achieved using CSS and the onmouseover event. I am including a snippet of code that ...

Guide to Repairing Uncaught TypeError: players.setAttribute is not a recognized method?

I'm a beginner and encountered an error saying Uncaught TypeError: players.setAttribute is not a function when submitting an action. How can I solve this issue? Please share your insights. ''' //selecting all necessary elements const s ...

Tips on modifying responsive design with jQuery

I have implemented a responsive design approach with the following CSS code: @media all and (max-width:799px){ .bigFont{ font-size: 28px; } } @media all and (min-width:800px){ .bigFont{ font-size: 48px; } } If I want to modify the font size using ...

Is it possible to center the image and resize it even when the window is resized?

My goal is to position an image in the center of the screen by performing some calculations. I've tried using: var wh = jQuery(window).innerHeight(); var ww = jQuery(window).innerWidth(); var fh = jQuery('.drop').innerHeight(); var fw = jQ ...

Tips for passing down CSS styles through Less stylesheets

In an effort to create a legend below a <table> that matches the colors defined in Bootstrap stylesheets, I am struggling with the following: .table > thead > tr > td.warning, .table > tbody > tr > td.warning, .table > tfoot ...

How do I make an image fill the entire space of a div using JQuery and CSS?

html: <body> <div class="custom-div"><input type="button" id="x" name="button" value="Search" onclick="showUser()" class="button"/></div> <input type="image" name="button" value="Search" onclick="showUser()" class="bu ...

Tips for getting the DIV:hover effect to work in Internet Explorer 8

Can someone provide me with the steps to get DIV:Hover functioning in Internet Explorer 8? ...

Center align text in the uib-progressbar

Is it possible to center align text in the uib-progressbar? I attempted using position:absolute, but I would like to display a list of progress bars in a UI grid that includes scrollable content. The goal is for the text to remain fixed while the progress ...

Troubles with aligning a figure in Bootstrap 4

I am in the process of updating my website layout from an old version marked by Old HTML, which can be found at JFiddle: https://jsfiddle.net/LybeppL3/11/ The new version I am working on, known as Current Code: https://jsfiddle.net/5c2sm9s1/23/ OR at Pree ...

Troubleshooting: Unable to fetch CSS file in Node.js Express framework

I'm trying to access my .html file with localhost using node.js, but I'm facing an issue with loading the CSS that is included in the file. I am using the express framework for this purpose. Code: var express = require('express'); var ...

What is the process for animating classes instead of ids in CSS?

My webpage currently features a setup similar to this. function wiggle(){ var parent = document.getElementById("wiggle"); var string = parent.innerHTML; parent.innerHTML = ""; string.split(""); var i = 0, length = string.length; for (i; i ...

currently experiencing layout discrepancies with Flexbox

Experimenting with flexbox has been challenging, but I am close to achieving my desired layout: Place a label in the top left of the first container Position a label in the top right of the first container Align a label in the bottom middle of the first ...

Ways to optimize the spacing between the menu bar and widgets

I have successfully incorporated multiple images side by side on my blog Following is the code used for this layout: <div class="images"> <figure> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSA7XLfGrT1rMS-Ifoguz-X2igsT ...

Using Angular to convert JSON data to PDF format and send it to the printer

Currently, I am retrieving JSON data from an API and now need to convert this data into a PDF format for printing. I am encountering an issue where the CSS styling for page breaks is not rendering properly within my Angular component. When I test the same ...

Ways to manipulate a div tag with CSS even when it lacks a class or ID attribute

Hey there! I've got this snippet of HTML code that I'm working with: <div class="template-page-wrapper"> <div class="templemo-content-wrapper"> <div class="templatemo-content"> <div c ...

Customizing the appearance of two separate tables

I have a pair of tables that I want to style differently. Table 1 needs the images centered with no border, while table 2 should have text left-aligned with a border. Here is the CSS: table, th, td { border: 1px solid #999; border-collapse: colla ...

Troubleshooting a vertical overflow problem with Flexbox

Struggling to design a portfolio page for FreeCodeCamp using flexbox layout due to vertical overflow issues. Here is the HTML: <div class="flex-container flex-column top"> <header class="flex-container"> <h1 class="logo"><i clas ...

Moving through divisions that share a common class name using jquery

I am experimenting with a plugin that allows me to attach popups to images. My goal is to enable navigation between all popups using previous and next buttons upon clicking on a popup. Below is the element when it's displayed: <div class="imp-too ...